Created
December 28, 2018 11:14
-
-
Save madis/e71d0eb0df721c16e9444b481cc50a14 to your computer and use it in GitHub Desktop.
Palindrome
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
# You can try the running code at http://tpcg.io/FnffuR | |
# More explicit implementation. The algorithm you described: | |
# iterating over characters from both ends of string. | |
# Returning false as soon as first mismatch is found | |
def palindrome_by_manual_reversing?(word) | |
word_string = word.to_s | |
# Return early because a word is always a palindrome if | |
# it is empty or of length 1 | |
return true if word_string.to_s.length <= 1 | |
length = word_string.length | |
middle_point = length % 2 == 0 ? length / 2 : (length - 1) / 2 | |
# Return true if any character from beginning and end doesn't match | |
(0...middle_point).any? do |index| | |
char_from_start = word_string[index] | |
char_from_end = word_string[(length - 1) - index] | |
char_from_start == char_from_end | |
end | |
end | |
# Simpler implementation relying on String#reverse and the fact | |
# that palindrome reads the same both ways | |
def palindrome?(word) | |
word.to_s == word.to_s.reverse | |
end | |
[ | |
"a", | |
"aa", | |
"aba", | |
"abb", | |
"kayak", | |
"racecar" | |
].each { |w| puts "Is '#{w}' a palindrome? #{palindrome?(w)} #{palindrome_by_manual_reversing?(w)}" } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output: