Skip to content

Instantly share code, notes, and snippets.

@madis
Created Dec 28, 2018
Embed
What would you like to do?
Palindrome
#!/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)}" }
@madis

This comment has been minimized.

Copy link
Owner Author

@madis madis commented Dec 28, 2018

Output:

$ruby main.rb
Is 'a' a palindrome? true true
Is 'aa' a palindrome? true true
Is 'aba' a palindrome? true true
Is 'abb' a palindrome? false false
Is 'kayak' a palindrome? true true
Is 'racecar' a palindrome? true true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment