Skip to content

Instantly share code, notes, and snippets.

@pragdave
Created March 28, 2013 22:47
Show Gist options
  • Save pragdave/5267474 to your computer and use it in GitHub Desktop.
Save pragdave/5267474 to your computer and use it in GitHub Desktop.
defmodule Anagram do
####
# given a word, return a list of anagrams
def anagrams_of(word) do
Keyword.get(dictionary, signature(word), [])
end
###
# Read in a dictionary file, and return a keyword list where
# the key is the signature of a word, and the value is a
# list of all the words sharing that signature
def dictionary do
word_list |> make_signatures |> hashify_dictionary
end
def word_list(from // "/usr/share/dict/words") do
IO.puts("start word list")
result = case File.read(from) do
{ :ok, all_words } ->
String.split(all_words, [" ", "\r", "\n"], [])
end
IO.puts("end word list")
result
end
# Given a list of words, return a list of [ signature, word ]
def make_signatures(words) do
IO.puts("start make_signatures")
result = lc word inlist words, do: [ signature(word), word ]
IO.puts("end make_signatures")
result
end
# the signature is the letters in the word, sorted
def signature(word) do
String.codepoints(word) |> Enum.sort |> list_to_binary |> binary_to_atom(:utf8)
end
###
# take a list of [ signature, word ] and create a hash
# where the key is the signature and the value is
# a list of all words with that signature
def hashify_dictionary(list) do
Enum.reduce list, [], fn([signature, word], hash) ->
case Keyword.get(hash, signature) do
nil -> Keyword.put(hash, signature, [ word ])
list -> Keyword.put(hash, signature, [ word | list ])
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment