Search code examples
rubyloopsreversepalindrome

Finding palindromes by adding its reversed to itself through x to y doing only depth number of calculation


I'm having trouble doing a challenge in ruby about palindromes.

I actually looked too many sources and i think my brain melted a bit as i am a novice programmer.

Lemme sum up the question :

So from user we get beginning value ending value, and a depth value.We take the beginning value and check If the number is a palindrome,if it isn't then we add its reversed to itself( 20, reverse(20)=02, add , 22) and check the number we find if its a palindrome.If it isn't we take the calculated number and add its reversed to itself.But we only can do that "depth" value times. And print if we find a palindrome through those calculations we print value ----> xxxx if not we print value ----> special number.

I'm able to find palindromes, through given and ending value.But i just cant implement the depth thing.My problem looks a lot like Setting a Limit on loops and calculating palindromes in C programming but since i'm a ruby novice i cant make sense of C for now.Any help will be appreciated.

Edit : We do that like x to y , beginning value to ending value, like if they type 20 as beginning and 30 as ending value, we check 20 if its a palindrome add its reversed etc.Once we finish checking it we check the next number, 21 then 22,23... to 30.


Solution

  • def doit(n, max_tries)
      max_tries.times.each do
        rev = n.to_s.reverse.to_i 
        (n == rev) ? (return n) : n += rev
      end
      nil
    end
    
    doit(22,   1)   #=> 22
    
    doit(21,   1)   #=> nil
    doit(21,   2)   #=> 33
    
    doit(137,  1)   #=> nil
    doit(137,  2)   #=> 868
    
    doit(1373, 2)   #=> nil 
    doit(1373, 3)   #=> 9119
    
    doit(13732,  9) #=> nil 
    doit(13732, 10) #=> 134202431