There are some different ways to look at what a palindrome is, and all of them can translate directly to code.
[For simplicity's sake, I will assume that the word
always gets passed as an Array
of downcase
d single-letter String
s, e.g. like palindrome?('Anna'.downcase.chars)
]
"A palindrome is the same forwards and backwards":
def palindrome?(word)
word == reverse(word)
end
This is of course the one you were thinking about, and the one the exam author wants to prohibit. Obviously, one way to "work around" this restriction is to implement the reversal method yourself.
Again, there are several different ways of thinking about reversing an array:
"Appending the first element to the reversed rest":
def reverse(ary)
return [] if ary.empty?
reverse(ary.drop(1)) + [ary.first]
end
"Prepending the last element to the reversed rest":
def reverse(ary)
return [] if ary.empty?
[ary.last] + reverse(ary[0...-1])
end
"The first and last letters are the same and the rest is a palindrome":
def palindrome?(word)
return true if word.empty?
word.first == word.last && palindrome?(word[1...-1])
end
My guess is that this, or something like this, is actually what the exam author was thinking about. However, by explicitly forbidding reverse
, they focus the student's mind on "How can I overcome not having reverse
" instead of "how could I interpret a palindrome differently". IOW: it's a bad exam question (if my guess is right).
Of course, there are even more ways to think about palindromes (and reversal), and there are some interesting optimizations given in other answers and comments.
return true if word_arr == reverse(word_arr)
to return explicitly and then 'false' at the end ofis_palindrome?
to return implicitly. I didn't think about it though! \$\endgroup\$