Skip to content

Instantly share code, notes, and snippets.

@lukemorton
Last active August 29, 2015 14:20
Show Gist options
  • Save lukemorton/a9e81810a4bc8477f371 to your computer and use it in GitHub Desktop.
Save lukemorton/a9e81810a4bc8477f371 to your computer and use it in GitHub Desktop.
class AnagramGrouper
def group
groups_larger_than_one(group_words(import('wordlist.txt')))
end
def group_words(words)
words.reduce({}) do |word_hash, word|
word = sanitize(word)
sorted = sort_word(word)
unless word_hash.has_key?(sorted)
word_hash[sorted] = []
end
unless word_hash[sorted].include?(word)
word_hash[sorted] << word.strip
end
word_hash
end.values
end
def import(filename)
File.open(filename).to_a
end
def sort_word(word)
word.split('').sort.join
end
def sanitize(word)
word.gsub('\'s', '').gsub(/[^a-zA-Z]+/, '').downcase
end
def groups_larger_than_one(groups)
groups.keep_if { |g| g.count > 1 }
end
end
class AnagramGrouper
extend self
def group
groups_larger_than_one(group_words(import('wordlist.txt')))
end
def group_words(words)
words.reduce({}) do |word_hash, word|
word = sanitize(word)
sorted = sort_word(word)
unless word_hash.has_key?(sorted)
word_hash[sorted] = []
end
unless word_hash[sorted].include?(word)
word_hash[sorted] << word.strip
end
word_hash
end.values
end
def import(filename)
File.open(filename).to_a
end
def sort_word(word)
word.split('').sort.join
end
def sanitize(word)
word.gsub('\'s', '').gsub(/[^a-zA-Z]+/, '').downcase
end
def groups_larger_than_one(groups)
groups.keep_if { |g| g.count > 1 }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment