Finding palindromic numbers in Ruby
So, I'm doing Project Euler to strengthen my Ruby skills. I am in issue # 4 which reads:
The palindromic number reads the same thing in both directions. The largest palindrome from the product of two two-digit numbers is 9009 = 91 * 99.
Find the largest palindrome from the product of two three-digit numbers.
First, I am trying to test my code using the information from the first paragraph. I have defined the palindrome function like this:
def palindrome?(blah)
string = blah.to_s
string.reverse == string
end
My code looks like this:
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 does not 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 am getting a long series of unsorted 4-digit numbers, so I guess this ignores sorting. Finally, if I just 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 as I should. Why is this happening?
I am using 1.8.6 because it is the only version available on this Windows machine.
You can use something like this
new_arr = array.inject ([]) {| a, u | a + = array.map {| y | u * y}}
instead
array = array.map {| u | array.map {| y | u * y}}
it returns a nested array "[[8100, ..], [], []]". So this is why your code is not working.
This line is your
array = array.map{|u| array.map{|y| u*y}}
returns a nested array, you must unpack.
Hints: (but I'm not going to tell you how)
- You probably don't need to sort by intermediate value
- You need to remove duplicates
Tips:
Next time, run your code in an interactive interpreter, so you can see the output of each line of code.
This looks clearer: -
#Steps
# Define a method for palindrome
# List out all 3-digit numbers
# Multiply each numbers by each numbers
# List out all palindrome numbers
# Choose the largest (max) palindrome number
def is_a_palindrome?(n)
n == n.to_s.reverse.to_i
end
def problem_four
palindrome = [ ]
array = 111.upto(999)
array.each do |x|
array.each do |y|
multiply = x * y
if is_a_palindrome?(multiply)
palindrome << multiply
end
end
end
palindrome.max
end
puts problem_four
#$ ruby problem_four.rb
#906609
Find the largest palindrome made from the product of two three-digit numbers.
I made this solution, hope it helps a newbie
to=999
from=100
palindromes=[]
for i in from..to do
for j in 1..to do
k=i*j
palindromes << k if k.to_s==k.to_s.reverse
end
end
palindromes.max #this will return 906609