ror dev newb - 4 months ago 14

Ruby Question

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

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('')

end

return x

end

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`

`999 - 1 * 999 - 1`

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.

Answer

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
end
end
max
```

(Note that the second index starting from `x`

rather than `100`

is just an optimization)

Source (Stackoverflow)

Comments