On Sep 4, 9:40=A0pm, RichardOnRails
<RichardDummyMailbox58... / uscomputergurus.com> wrote:
> Hi All,
>
> My middle-school granddaughter posed the following challenge to me:
>
> Within 10 minutes, Use the digits 3 to 7 in any order
> to form a three-digit multiplicand and a two-digit multiplier
> such that their product is minimal.
>
> Out of curiosity as to whether my guess was right,
> and with a view toward eliciting an interest in her
> for Ruby programming, =A0I wrote the program posted athttp://www.pastie.o=
rg/266447
>
> The program reveals that I was wrong, but it took me about 40 lines of
> code,
> ignoring comments. =A0That would probably overwhelm her. =A0I was hoping
> that
> the code could be condensed with Ruby-isms. =A0BTW, I left some put=92s i=
n
> there
> intended to give her a sense of the programs functionality.
>
> Any ideas/suggestions?


Here's one solution that requires the 'permutation' gem:

=3D=3D=3D=3D

require 'rubygems'
require 'permutation'

perm =3D Permutation.for((3..7).to_a)

min_product =3D 10**5
min_values =3D nil

perm.map do |p|
  a =3D p.project
  v1 =3D a[0, 3].to_s.to_i
  v2 =3D a[3, 2].to_s.to_i
  product =3D v1 * v2
  if product < min_product
    min_product =3D product
    min_values =3D [v1, v2]
  end
end

puts "#{min_values.first} * #{min_values.last} =3D #{min_product}"

=3D=3D=3D=3D

Eric

=3D=3D=3D=3D

Are you interested in on-site Ruby or Ruby on Rails training
that uses well-designed, real-world, hands-on exercises?
http://LearnRuby.co