Skip to content

Instantly share code, notes, and snippets.

@armandocanals
Last active December 14, 2015 12:18
Show Gist options
  • Save armandocanals/5085378 to your computer and use it in GitHub Desktop.
Save armandocanals/5085378 to your computer and use it in GitHub Desktop.
Group all words that are anagrams of one another
#!/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