From: RichardOnRails Date: 2008-09-05T15:44:14+09:00 Subject: Re: Need a 40 LOC (ignoring comments) to be shorter -- suggestions wanted On Sep 5, 1:34 am, "Eric I." wrote: > On Sep 4, 9:40 pm, RichardOnRails > > > > 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,  I wrote the program posted athttp://www.pastie.org/266447 > > > The program reveals that I was wrong, but it took me about 40 lines of > > code, > > ignoring comments.  That would probably overwhelm her.  I was hoping > > that > > the code could be condensed with Ruby-isms.  BTW, I left some put’s in > > there > > intended to give her a sense of the programs functionality. > > > Any ideas/suggestions? > > Here's one solution that requires the 'permutation' gem: > > ==== > > require 'rubygems' > require 'permutation' > > perm = Permutation.for((3..7).to_a) > > min_product = 10**5 > min_values = nil > > perm.map do |p| >   a = p.project >   v1 = a[0, 3].to_s.to_i >   v2 = a[3, 2].to_s.to_i >   product = v1 * v2 >   if product < min_product >     min_product = product >     min_values = [v1, v2] >   end > end > > puts "#{min_values.first} * #{min_values.last} = #{min_product}" > > ==== > > Eric > > ==== > > Are you interested in on-site Ruby or Ruby on Rails training > that uses well-designed, real-world, hands-on exercises?http://LearnRuby.co Thanks, Eric, I should have thought of looking for that. I certainly know I was analyzing 5! permutations. My granddaughter is much more likely to delve into that a little ways. I doesn't look so intimidating :-) Best wishes, Richard