I’m new to Ruby and was trying to do one simple exercise.
I need to find the longest symmetric range inside an array.
My code is:
index_start = index_end = nil
max_length = 0
array = [1,2,3,4,5,6,6,5,4,3,2,1]
length = array.length
array.each_with_index do |outer_element, outer_index|
array.reverse.each_with_index do |inner_element, inner_index|
if outer_element.eql? inner_element
end_index = length - 1 - inner_index
tmp_array = array[outer_index..end_index]
if tmp_array.eql? tmp_array.reverse and max_length < tmp_array.length
index_start, index_end = outer_index, end_index
max_length = tmp_array.length
end
end
end
end
print max_length, "\n"
print index_start,' ', index_end, "\n"
unless max_length.eql? 0
print array[index_start..index_end]
end
The problem is this: after the second iteration by the inner loop, the inner_index variable becomes equal to 11, while it has to be 1 and this is happening after the if outer_element.eql? inner_element statement.
I’m a little bit confused about what I’m doing wrong.
Excuse my English and Ruby, I’m new to both. Thanks a lot for your help!
You are missing a
in the case you found a new longest symmetric sub-array.
With the current code,
max_lengthis always 0 and the last one-element sub-array ([1]) is symmetric and longer than 0.So the code should be: