Beginner's Elixir version of Avdi's anagram for Hello Crystal http://devblog.avdi.org/2015/08/20/hello-crystal/
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
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample benchmark: