Skip to content

Instantly share code, notes, and snippets.

@bbonamin
Created September 17, 2015 19:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bbonamin/475152ca5ff93aa8dcc5 to your computer and use it in GitHub Desktop.
Save bbonamin/475152ca5ff93aa8dcc5 to your computer and use it in GitHub Desktop.
Beginner's Elixir version of Avdi's anagram for Hello Crystal http://devblog.avdi.org/2015/08/20/hello-crystal/
defmodule Anagram do
def table(file, table) do
case IO.read(file, :line) do
line when line != :eof ->
word = String.replace(line, ~r/\n/, "")
key = to_key(word)
row = table[key] || []
row = row ++ [String.downcase(word)]
table = Dict.put(table, key, row)
table(file, table)
_ ->
File.close(file)
table
end
end
def to_key word do
word
|> String.downcase
|> String.to_char_list
|> Enum.sort
|> List.to_string
end
end
{:ok, file} = File.open "/usr/share/dict/words"
table = Anagram.table(file, Map.new)
[ word | _ ] = System.argv
word = String.downcase(word)
key = Anagram.to_key word
anagrams = List.delete table[key], word
if Enum.empty?(anagrams) do
IO.puts "Sorry, no anagrams for '#{word}'"
else
IO.puts "Anagrams for '#{word}': #{Enum.join(anagrams, ", ")}"
end
@rdp
Copy link

rdp commented Sep 18, 2015

benchmarks vs. avdi and ruby?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment