Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding palindromic numbers in Ruby

Tags:

ruby

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.

like image 963
PreciousBodilyFluids Avatar asked Jun 18 '26 16:06

PreciousBodilyFluids


2 Answers

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.

like image 197
RichN Avatar answered Jun 21 '26 06:06

RichN


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

like image 36
Rishav Rastogi Avatar answered Jun 21 '26 06:06

Rishav Rastogi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!