views:

308

answers:

2

So, I'm doing Project Euler to solidify my Ruby skills. I'm on problem #4, which reads:

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 * 99.

Find the largest palindrome made from the product of two 3-digit numbers.

First, I'm trying to verify my code using the information from the first paragraph. I've defined a palindrome function as so:

def palindrome?(blah)
  string = blah.to_s
  string.reverse == string
end

My code looks like:

array = (90..99).to_a
array = array.map{|u| array.map{|y| u*y}}
array = array.sort
array = array.select{|u| palindrome?(u)}
puts array

The program doesn't output anything. If I do the following:

array = (90..99).to_a
array = array.map{|u| array.map{|y| u*y}}
array = array.sort
#array = array.select{|u| palindrome?(u)}
puts array

I get a long series of unsorted four-digit numbers, so I guess it's ignoring the sort. Finally, if I simply do:

#array = (90..99).to_a
#array = array.map{|u| array.map{|y| u*y}}
#array = array.sort

array = [7447, 9009, 3551, 2419]
array = array.select{|u| palindrome?(u)}
puts array

I get 7447 and 9009, like I should. Why is this happening?

I'm using 1.8.6, because that's the only version available on this Windows machine.

+2  A: 

This line of yours

array = array.map{|u| array.map{|y| u*y}}

returns a nested array, you should unwrap.

Hints: (but I'm not going to tell you how)

  1. You probably don't need sort on the intermediary value
  2. You need to remove duplicates

Tips:
next time, run your code in the interactive interpreter, that way you'll see the result of each line of code.

RichN
+1  A: 

You can use something like this


 new_arr = array.inject([]) { |a,u| a += array.map { |y| u*y } }

instead of

  array = array.map{|u| array.map{|y| u*y}}

it returns a nested "[ [8100,..],[],[] ] " type of array. So thats the reason why your code doesn't work

Rishav Rastogi
ARGH, of course. When I decided on the dual mapping approach I used, I figured I'd just flatten the nested arrays afterward... and then I completely forgot. Sigh.Anyway, changed line 3 to array = array.flatten.sort and it works great. Oh well.Thanks!
PreciousBodilyFluids