Last active
August 29, 2015 14:01
-
-
Save dougyoung/aa1eaa0e2543a8ffbb99 to your computer and use it in GitHub Desktop.
Anagram discoverer in Ruby
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
require 'set' | |
class Anagram | |
DefaultWordlist = (File.open '/usr/share/dict/words' rescue []) | |
.inject(Set.new) { |s, word| s << word.downcase.chomp } | |
def initialize(wordlist = DefaultWordlist) | |
@wordlist_signed = wordlist | |
.inject(Hash.new { [] }) { |h, word| h[sign(word)] <<= word; h } | |
end | |
def solve(word) | |
@wordlist_signed[sign(word)] - [word] | |
end | |
private | |
def sign(word) | |
word.downcase.chars.sort.join | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment