Created
August 23, 2012 16:08
-
-
Save randito/3438114 to your computer and use it in GitHub Desktop.
Little anagram checker. Had to find out if this tweet was true: https://twitter.com/crampell/status/238620771398864897
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
class String | |
def anagram?(other) | |
letter_count(self) == letter_count(other) # uses hash equivelence | |
end | |
private | |
# "wwaax" => { "w" => 2, "a" => 2, "x" => 1 }.. all others 0 | |
def letter_count(str) | |
str.downcase.each_char.inject(Hash.new(0)) { |h, ch| h[ch] += 1; h } | |
end | |
end | |
unless defined?(assert) | |
def assert(cond, msg="Failed assertion") | |
raise msg unless cond | |
end | |
end | |
assert "abc".anagram?("cba") | |
assert "Abc".anagram?("Cba") | |
assert !"xxx".anagram?("monkey") | |
# https://twitter.com/crampell/status/238620771398864897 | |
assert "My Ultimate Ayn Rand Porn".anagram?("Mitt Romney and Paul Ryan") |
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
# 1.9 version courtesy of @bheeshmar | |
class String | |
def anagram?(other) | |
raise "Fail!" unless RUBY_VERSION =~ /1.9/ | |
self.downcase.chars.sort == other.downcase.chars.sort | |
end | |
end | |
# 1.9.2p290 :008 > "abc".anagram?("cba") | |
# => true | |
# 1.9.2p290 :009 > "abc".anagram?("xxx") | |
# => false |
Bheesh is the weiner here. Opps, I meant winner.
Sorry Bheesh. Doesn't work in 1.8.7.
>> "abc".sort == "cba".sort
=> false
But, a variant does work in 1.9.
class String
def anagram?(other)
raise "Fail!" unless RUBY_VERSION =~ /1.9/
self.downcase.chars.sort == other.downcase.chars.sort
end
end
1.9.2p290 :008 > "abc".anagram?("cba")
=> true
1.9.2p290 :009 > "abc".anagram?("xxx")
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
class String
def anagram?(other)
self.downcase.sort == other.downcase.sort
end
end