Last active
November 16, 2017 09:54
-
-
Save styd/8545cac8eb46640c3fedb7e7be538901 to your computer and use it in GitHub Desktop.
Strict and non-strict palindrome. Default is not strict.
This file contains hidden or 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 | |
class String | |
def palindrome?(strict = false) | |
return true if length.zero? || length == 1 | |
i = -1 | |
j = length | |
length.times do | |
loop do | |
i += 1 | |
break if strict || self[i] =~ /[A-z0-9]/ | |
end | |
loop do | |
j -= 1 | |
break if strict || self[j] =~ /[A-z0-9]/ | |
end | |
return false unless self[i].casecmp(self[j]).zero? | |
return true if i >= j - 2 | |
end | |
return false | |
end | |
end | |
# palindromic poem by Demetri Martin | |
poem = <<~POEM | |
Dammit I'm mad. | |
Evil is a deed as I live. | |
God, am I reviled? I rise, my bed on a sun, I melt. | |
To be not one man emanating is sad. I piss. | |
Alas, it is so late. Who stops to help? | |
Man, it is hot. I'm in it. I tell. | |
I am not a devil. I level "Mad Dog". | |
Ah, say burning is, as a deified gulp, | |
In my halo of a mired rum tin. | |
I erase many men. Oh, to be man, a sin. | |
Is evil in a clam? In a trap? | |
No. It is open. On it I was stuck. | |
Rats peed on hope. Elsewhere dips a web. | |
Be still if I fill its ebb. | |
Ew, a spider… eh? | |
We sleep. Oh no! | |
Deep, stark cuts saw it in one position. | |
Part animal, can I live? Sin is a name. | |
Both, one… my names are in it. | |
Murder? I'm a fool. | |
A hymn I plug, deified as a sign in ruby ash, | |
A Goddam level I lived at. | |
On mail let it in. I'm it. | |
Oh, sit in ample hot spots. Oh wet! | |
A loss it is alas (sip). I'd assign it a name. | |
Name not one bottle minus an ode by me: | |
"Sir, I deliver. I'm a dog" | |
Evil is a deed as I live. | |
Dammit I'm mad. | |
POEM | |
# `if poem.palindrome? true` for strict palindrome check. | |
check = if poem.palindrome? # non-strict palindrome check. | |
"Yay! A palindrome." | |
else | |
"Sadly, not a palindrome." | |
end | |
puts check |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment