Last active
August 29, 2015 14:20
-
-
Save lukemorton/a9e81810a4bc8477f371 to your computer and use it in GitHub Desktop.
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
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 |
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
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