I am trying to develop a function which will return the longest palindrome substring of an entered string. I am right now working on breaking up the string so that each subsection could then be analyzed to see if it is a palindromeThe code is as follows:
def longest_palindrome(s)
place = 0
array = s.chars
output = []
while place < s.length
output << (array[0]..array[place]).to_a
place += 1
end
return output
end
if given string "ababa" I would expect the resulting array to look like this:
[["a"],["a","b"],["a","b","a"],["a","b","a","b"],["a","b","a","b","a"]]
However, when i return the output array this is what is stored inside:
[["a"], ["a", "b"], ["a"], ["a", "b"], ["a"], ["a", "b"]]
What about my function is causing this to happen?
Edit:
Not sure if I should start another topic for this. My code is now as follows:
def longest_palindrome(s)
array = s.chars
start = 0
place = 1
output = []
while start < s.length - 1
while place < s.length
output << array[start..place]
place += 1
end
start += 1
end
return output
end
My logic is that this will start at index 0, then progressively capture one character more of the string until the whole string is complete. Then it will start on index 1 and do the same until it has gotten all possible substrings within the string. However, it only returns:
[["a"],["a","b"],["a","b","a"],["a","b","a","b"],["a","b","a","b","a"]]
Where is the flaw in my logic?
You're misusing the range operator to produce ranges like 'a'..'a'
, which is just 'a'
.
You have two completely independent array indexing operations, each of which return a single element (character) from the array to be used in a range. You're getting array[0]
, which is always a
, and array[place]
which alternates between a
and b
, and producing the ranges 'a'..'a'
and 'a'..'b'
over and over, which have nothing to do with the arrays the characters originally came from.
You can't build the ranges after extracting the elements from the array and expect the ranges to be produced from the array. The correct sub-array is produced by using the range as the index of the array: array[0..place]
. This returns the sub-array from 0
to place
, inclusive.