Skip to content

Instantly share code, notes, and snippets.

@dougyoung
Last active August 29, 2015 14:01
Show Gist options
  • Save dougyoung/aa1eaa0e2543a8ffbb99 to your computer and use it in GitHub Desktop.
Save dougyoung/aa1eaa0e2543a8ffbb99 to your computer and use it in GitHub Desktop.
Anagram discoverer in Ruby
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