Largest palindrome product - Ruby

0

How to make this code faster? It works, but not fast enough.

#!/bin/ruby

def isPalin(mul)
  if mul.to_s == mul.to_s.reverse then
    return true
  else
    return false
  end
end

def lp(n)
  arr = []

  for a1 in (100..999)
    for a2 in (100..999)
      mul = a1*a2
      break if mul > n
      if mul <= n then
        arr.push(mul) if isPalin(mul)
      end
    end
  end

  arr.sort!
  puts arr[arr.length-1]

end


t = gets.strip.to_i
for a0 in (0..t-1)
  n = gets.strip.to_i

  lp(n)
end

Thanks for your help!

    
asked by anonymous 20.10.2016 / 19:04

1 answer

0

The double for loop does folded work: n1 * n2 == n2 * n1. Use the outside index on the inside loop to avoid repetition.

(100..999).each do |n1| (n1..999).each do |n2| mul = n1 * n2 if mul <= n arr << mul if palindromo?(mul.to_s) else break end end end

each is an Enumerable method, inherited by Array. See the documentation.

The isPalin function can be simplified, starting by cutting if ... then true else false :

def isPalin(mul) return mul.to_s == mul.to_s.reverse end

Up to return end can be cut, leaving only the expression, because the function will return the last calculated value.

If you assume that the value is already a string, you can use the fact that strings have their characters indexed, and admit negative indexes:

def palindromo?(s) tam = s.size return true if tam < 2 return (0..(tam/2)).all? { |i| s[i] == s[tam - i - 1] } end

all? is another Enumerable method: returns true if all enumerable elements return true when applied to the block.

    
21.11.2016 / 20:51