37 lines
1.1 KiB
Elixir
37 lines
1.1 KiB
Elixir
defmodule Day1 do
|
|
def part1(file_path) do
|
|
file_path
|
|
|> File.read!()
|
|
|> String.split("\n")
|
|
|> Enum.map(&String.split/1)
|
|
|> Enum.filter(fn list -> length(list) == 2 end)
|
|
|> Enum.map(fn [a, b] -> {String.to_integer(a), String.to_integer(b)} end)
|
|
|> Enum.unzip()
|
|
|> Tuple.to_list()
|
|
|> Enum.map(&Enum.sort/1)
|
|
|> Enum.zip()
|
|
|> Enum.map(fn {a, b} -> abs(a - b) end)
|
|
|> Enum.sum()
|
|
end
|
|
|
|
def part2(file_path) do
|
|
file_path
|
|
|> File.read!()
|
|
|> String.split("\n")
|
|
|> Enum.map(&String.split/1)
|
|
|> Enum.filter(fn list -> length(list) == 2 end)
|
|
|> Enum.map(fn [a, b] -> {String.to_integer(a), String.to_integer(b)} end)
|
|
|> Enum.unzip()
|
|
|> Tuple.to_list()
|
|
|> Enum.map(&Enum.sort/1)
|
|
|> (fn [list1, list2] -> {list1, Enum.frequencies(list2)} end).()
|
|
|> (fn {list1, freqs} ->
|
|
list1
|
|
|> Enum.map(&{&1, Map.get(freqs, &1, 0)})
|
|
|> Enum.filter(fn {_, count} -> count != 0 end)
|
|
|> Enum.map(fn {value, count} -> value * count end)
|
|
end).()
|
|
|> Enum.sum()
|
|
end
|
|
end
|