-
Notifications
You must be signed in to change notification settings - Fork 0
/
anagrams_dist.exs
48 lines (33 loc) · 1012 Bytes
/
anagrams_dist.exs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
defmodule Dictionary do
@name { :global, __MODULE__ }
#########
# External API
def start_link, do:
Agent.start_link(fn -> %{} end, name: @name)
def add_words(words), do:
Agent.update(@name, &do_add_words(&1, words))
def anagrams_of(word), do:
Agent.get(@name, &Map.get(&1, signature_of(word)))
##########
# Internal Implementation
defp do_add_words(map, words), do:
Enum.reduce(words, map, &add_one_word(&1, &2))
defp add_one_word(word, map), do:
Map.update(map, signature_of(word), [word], &[word|&1])
defp signature_of(word), do:
word |> to_charlist |> Enum.sort |> to_string
end
defmodule WordlistLoader do
def load_from_files(file_names) do
file_names
|> Stream.map(fn name ->
Task.async(fn -> load_task(name) end)
end)
|> Enum.map(&Task.await/1)
end
defp load_task(file_name) do
File.stream!(file_name, [], :line)
|> Enum.map(&String.strip/1)
|> Dictionary.add_words
end
end