Last active
December 14, 2015 12:18
-
-
Save armandocanals/5085378 to your computer and use it in GitHub Desktop.
Group all words that are anagrams of one another
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/ruby | |
# Group all words that are anagrams of one another | |
# example: | |
# sample set of words | |
# dict = %w[cat tar war store core orb bro rat] | |
# $ ruby anagram.rb | |
# expect | |
# { | |
# "act"=>["cat"], | |
# "art"=>["tar", "rat"], | |
# "arw"=>["war"], | |
# "eorst"=>["store"], | |
# "ceor"=>["core"], | |
# "bor"=>["orb", "bro"] | |
# } | |
dict = File.read('/usr/share/dict/words').split("\n") | |
hsh = {} | |
dict.each do |word| | |
word = word.downcase | |
sorted_word = word.chars.sort.join('') | |
hsh[sorted_word] ||= [] | |
if hsh.keys.include?(sorted_word) | |
hsh[sorted_word] << word | |
end | |
end | |
p hsh | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment