Powered by AppSignal & Oban Pro
Would you like to see your link here? Contact us

Day 1

day1.livemd

Day 1

Mix.install([
  {:kino, "~> 0.14.2"}
])

Part 1

input = Kino.FS.file_path("input.txt") |> File.read!()
interspersed_lists = String.trim(input)
  |> String.split("\n") 
  |> Enum.flat_map(fn pairs -> String.split(pairs) end) 
  |> Enum.map(fn val -> String.to_integer(val) end)
{sorted_a, sorted_b} = {
  Enum.take_every(interspersed_lists, 2) |> Enum.sort(),
  Enum.drop_every(interspersed_lists, 2) |> Enum.sort()
}
diff = Enum.zip([sorted_a, sorted_b])
  |> Enum.map(fn {a, b} -> abs(a - b) end)
  |> Enum.sum()

Part 2

frequencies = Enum.frequencies(sorted_b)
sum = Enum.map(sorted_a, fn elem -> elem * Map.get(frequencies, elem, 0) end) 
  |> Enum.sum()