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

Day 1: Historian Hysteria

2024/day_01.livemd

Day 1: Historian Hysteria

Mix.install([:kino])

input = Kino.Input.textarea("Please paste your input:")

Part 1

Run in Livebook

https://adventofcode.com/2024/day/1

data =
  input
  |> Kino.Input.read()
  |> String.split("\n", trim: true)
pairs =
  data
  |> Enum.map(fn line -> String.split(line) |> Enum.map(&String.to_integer/1) end)

[sorted_lefts, sorted_rights] =
  pairs
  |> Enum.zip_with(& &1)

_answer =
  [sorted_lefts, sorted_rights]
  |> Enum.zip_with(fn [left, right] -> abs(left - right) end)
  |> Enum.sum()

Part 2

https://adventofcode.com/2024/day/1#part2

left_frequencies =
  sorted_lefts
  |> Enum.frequencies()

right_frequencies =
  sorted_rights
  |> Enum.frequencies()

_answer =
  left_frequencies
  |> Enum.map(fn {number, left_frequency} ->
    right_frequency = right_frequencies |> Map.get(number, 0)

    number * left_frequency * right_frequency
  end)
  |> Enum.sum()