Ruby longest palindrome - why does a slight modification in a while loop break my code? -
i'm trying solve ruby problem , can't figure out why having minor while loop difference renders 1 test false: longest_palindrome("abba") outputs "bb" instead of "abba", false. can solve , while loops, please no advanced methods. it's easier highlight difference in code block (first 1 working solution, second mine. assume palindrome?
method defined):
def longest_palindrome(string) best_palindrome = nil idx1 = 0 ***while idx1 < string.length length = 1 while (idx1 + length) <= string.length substring = string.slice(idx1, length)*** if palindrome?(substring) && (best_palindrome == nil || substring.length > best_palindrome.length) best_palindrome = substring end length += 1 end idx1 += 1 end return best_palindrome end def longest_palindrome(string) longest = nil = 0 ***while < string.length i2 = 1 while i2 < string.length*** if palindrome?(string.slice(i, i2)) == true && (longest == nil || string.slice(i, i2).length > longest.length) longest = string.slice(i, i2) end i2 += 1 end += 1 end return longest end
this part of code...
while i2 < string.length
... means you're never checking maximum possible length.
"abba".slice(0,4)
entire string, ever go "abba".slice(0,3)
"abb".
so never test entire string.
change line to...
while i2 <= string.length
...and should ok.
Comments
Post a Comment