ror dev newb ror dev newb - 1 year ago 59
Ruby Question

Ruby - decrease integers from params one by one and loop with those

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.
I am very new to Ruby and coding, so struggling with this one quite a while. Here is what I have:

def biggest(num, num2)
total = num * num2
x = total.to_s.split('')

until x[0] == x[-1] && x[1] == x[-2] && x[2] == x[-3]
num = num - 1
num2 = num2 - 1
total = num * num2
x = total.to_s.split('')

return x

p biggest(999, 999)

Problem is that this decreases both params at the same time and gives a wrong answer. I think I should decrease only one number at a time:
999 - 1 * 999
, and if not meets condition, decrease other:
999 - 1 * 999 - 1
. And keep looping like this until true.

I know this is not the best approach to this method. It I think it is even wrong from mathematical aspect, but I am just learning, so I kindly ask to give me some insights how this code could be improved. Any optional approaches are very welcome but most important for me is how to fix my mistakes made here.

ndn ndn
Answer Source

As you found out yourself, the main reason why your implementation doesn't work is because you decrement both num and num2 thus iterating over [i, i] pairs rather than [i, j].

Your second issue is that even if you did decrement them one after the other, your until still assumes that the solution must be a [n0, m0] pair, where max(n0, m0) >= max(ni, mj), for ∀ni, mj: ni ∈ 100..999, mj ∈ 100..999 and ni * mj is palindrome.

Your third problem is stylistic - Ruby is a higher level language, yet you do comparison of characters manually. Here is a possible solution:

max = 0

100.upto(999) do |x|
  x.upto(999) do |y|
    product = x * y
    max = product if product > max and product.to_s.reverse.to_i == product


(Note that the second index starting from x rather than 100 is just an optimization)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download