Basically, what I’m trying to do is that I want a map where the key is a tuple containing count of all same characters in the list and its values being the list of anagrams. To explain it in more clearer terms, I want the following:
%{{0, 0, 0, 0, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0} => ['eggs', 'gegs'], {1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0} => ['clay', 'alcy']}
Now, currently what I am getting is the following:
%{ {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0} => "y", {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0} => "s", {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} => "l", {0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} => "g", {0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} => "e", {0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} => "c", {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} => "a" }
I basically got this by writing the following code:
defmodule Anagram do
def traverse(strings, acc \\ Map.new()) do
Enum.reduce(strings, acc, fn string, acc ->
string
|> String.graphemes()
|> Enum.reduce(acc, &Anagram.fun/2)
end)
end
def fun(char, acc) do
{index, _} = :binary.match("abcdefghijklmnopqrstuvwxyz", char)
count = List.duplicate(0, 26)
count = List.update_at(count, index, &(&1 + 1))
tupcount = List.to_tuple(count)
Map.update(acc, tupcount, count, fn _ -> char end)
end
end
IO.inspect Anagram.traverse ["eggs", "gegs", "clay", "alcy"]
Any idea what needs to be corrected here? I’m pretty new to Elixir and experimenting with different stuff but I’m a little lost over here. Any help will be appreciated.