Skip to content

Instantly share code, notes, and snippets.

@bbonamin
Created Sep 17, 2015
Embed
What would you like to do?
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
@bbonamin
Copy link
Author

bbonamin commented Sep 17, 2015

Sample benchmark:

elixir_first_steps|master⚡ ⇒ time elixir anagram.exs "avdi"
Anagrams for 'avdi': avid, diva
elixir anagram.exs "avdi"  11.30s user 0.45s system 100% cpu 11.727 total

@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