Skip to content

Instantly share code, notes, and snippets.

@madis
Created December 28, 2018 11:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save madis/e71d0eb0df721c16e9444b481cc50a14 to your computer and use it in GitHub Desktop.
Save madis/e71d0eb0df721c16e9444b481cc50a14 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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