2

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.

4

2 回答 2

2

乍一看,这是因为当 i*j 不是回文时, palintest(i*j) 返回 nil。

快速解决 :

puts palindromes.reject(&:nil?).max
于 2015-06-09T00:12:59.670 回答
1

您有一堆要添加到数组中的 nil。Max 不能使用 nils - 它比较每个元素。只需添加palindromes << palintest(i*j) if palintest(i*j)

但实际上可能读起来更好:

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
于 2015-06-09T00:50:06.010 回答