Skip to content

Instantly share code, notes, and snippets.

@lachlan
Created September 28, 2012 00:33
Show Gist options
  • Save lachlan/3797281 to your computer and use it in GitHub Desktop.
Save lachlan/3797281 to your computer and use it in GitHub Desktop.
Find all the anagrams in a dictionary file
filename = "words.txt"
words = []
class String
def is_anagram?(other)
self.length == other.length && self.chars.sort == other.chars.sort
end
end
# build a list words from the file
File.open(filename, "r") do |file|
file.each_line do |line|
word = line.strip.downcase
words << word unless word.empty?
end
end
# get rid of duplicates
words.uniq!
# build a list of anagrams
hash = {}
words.each do |word|
# calculate a key that all anagrams will match by sorting the chars in
# alphabetical order
key = word.chars.sort
# get the list of words that match this key, or an empty array if this is the first
list = hash[key] || []
# append word to the list of words for this anagram
list << word
# write the list back to the table
hash[key] = list
end
# remove all words without anagrams
hash.select! do |key, value|
value.length > 1
end
anagrams = hash.values
# sort by the number of anagrams descending
anagrams.sort! do |a, b|
b.length - a.length
end
puts "# of anagrams found: " + anagrams.length.to_s
anagrams.each do |list|
puts list.join(", ")
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment