From: RichardOnRails Date: 2008-09-07T10:19:03+09:00 Subject: Re: Need a 40 LOC (ignoring comments) to be shorter -- suggestions wanted On Sep 5, 3:30 am, Lars Christensen wrote: > On Sep 5, 7:34 am, "Eric I." wrote: > > > On Sep 4, 9:40 pm, RichardOnRails > > > Any ideas/suggestions? > > > Here's one solution that requires the 'permutation' gem: > > Ruby 1.8.7 and 1.9 has Array#permutation: > > (3..7).to_a.permutation.sort_by { |a| a[0..2].to_s.to_i * > a[3..4].to_s.to_i }.first > > Golf anyone? :-) > > Lars Hi Lars, If this were the Olympics for succinct Ruby, you’d get the Gold!! Thanks for this expression. > Ruby 1.8.7 and 1.9 has Array#permutation: I’m running ruby 1.8.6, so of course “(3..7).to_a.permutation” failed My work-around (which produced a correct result) is: a=[]; Permutation.new(5).each { |p| a << ((p.value.to_s.to_i + 3333).to_s) => 34567, 34576, 34657, 34675, 34756, 34765, 35467, [snip] a.sort_by { |a| (a[0..2].to_s.to_i )*(a[3..4].to_s.to_i) }.first => 46735 Note that I compensated for the (3..7) ... construct not working by adding 33333 to each permutation. Also, I had to fix one blemish: parentheses were needed around the multiplicative factors; a radix diagnostic was issued without them.. Maybe it’s another 1.8.6 problem Again, thanks for this neat construct. I’m going to introduce to my granddaughter as a first step of a programmed solution to the problem she presented. But then, I’ll admit it takes a Ruby pro to achieve that level of brevity. I’ll follow that with my more mundane approach and see whether she’ll hang in there until achieving a glimmer of insight into Ruby programming. If you have any more enlightenment on these issues, I’d be pleased to receive them. Best wishes, Richard