I was working on a program for question 4 in Project Euler - find the largest palindrome among multiples of 3-digit numbers. This is what I wrote:
def palintest(number)
num = number.to_s
len = num.length
if len % 2 != 0
num[(len/2).floor] = ''
end
if num[0.. (len/2)-1] == num [len/2..len].reverse!
return number
end
end
palindromes = []
for i in 100..999
for j in 100..999
palindromes << palintest(i*j)
end
end
puts palindromes.max
I got an error that says:
comparison of Fixnum with nil failed
(repl):24:in `each'
(repl):24:in `max'
(repl):24:in `initialize'
I can't really figure out what's going on, I've tested each component of the program and it seems to be in working order. Any help would be appreciated.
You have a bunch of nils that you are adding to your array. Max can't work with nils - it compares each element. Just add palindromes << palintest(i*j) if palintest(i*j)
But really might read better like:
def palindrome?(number)
num = number.to_s
len = num.length
num[(len/2).floor] = '' unless len.even?
num[0..(len/2)-1] == num[len/2..len].reverse # return boolean
end
palindromes = []
for i in 100..999
for j in 100..999
palindromes << (i * j) if palindrome?(i * j)
end
end
puts palindromes.max