Mix.install([
{:kino, "~> 0.11.0"}
])
data = Kino.Input.textarea("Daily input")
input = Kino.Input.read(data)
{list1, list2} =
input
|> String.split("\n", trim: true)
|> Enum.map(fn line ->
line
|> String.split()
|> Enum.map(&String.to_integer/1)
|> List.to_tuple()
end)
|> Enum.unzip()
|> then(fn {list1, list2} ->
{Enum.sort(list1), Enum.sort(list2)}
end)
Enum.zip_reduce(list1, list2, 0, fn a, b, acc ->
acc + abs(a - b)
end)
I asked ChatGPT if what I am doing is efficient and it was not. This is what it suggested to do instead. Makes sense to first count list 2 and then "just" Map.get() that count instead of re-counting every step along the way.
counts =
Enum.reduce(list2, %{}, fn x, acc ->
Map.update(acc, x, 1, &(&1 + 1))
end)
result =
Enum.reduce(list1, 0, fn number, acc ->
# Get count from map (default to 0)
appearance = Map.get(counts, number, 0)
acc + number * appearance
end)