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

Advent of Code - 2024 Day 11

2024/day-11.livemd

Advent of Code - 2024 Day 11

Mix.install([
  {:kino_aoc, "~> 0.1.7"},
  {:benchee, "~> 1.3"}
])

Section

{:ok, puzzle_input} =
  KinoAOC.download_puzzle("2024", "11", System.fetch_env!("LB_AOC_SESSION"))
test_input = "0 1 10 99 999"
stones = puzzle_input |> String.split() |> Enum.map(&String.to_integer/1)
transform = fn
  0 ->
    [1]

  n ->
    len = floor(:math.log10(n)) + 1

    if Bitwise.band(len, 1) == 1 do
      [n * 2024]
    else
      d = 10 ** Bitwise.bsr(len, 1)
      [div(n, d), rem(n, d)]
    end
end
stones
|> Enum.frequencies()
|> Stream.iterate(fn freqs ->
  for {num, freq} <- freqs, num2 <- transform.(num), reduce: %{} do
    freqs2 -> Map.update(freqs2, num2, freq, &amp; &amp;1 + freq)
  end
end)
|> Enum.at(75)
|> Map.values()
|> Enum.sum()
Benchee.run(%{
  "Part 2": fn ->
    stones
    |> Enum.frequencies()
    |> Stream.iterate(fn freqs ->
      for {num, freq} <- freqs, num2 <- transform.(num), reduce: %{} do
        freqs2 -> Map.update(freqs2, num2, freq, &amp; &amp;1 + freq)
      end
    end)
    |> Enum.at(75)
    |> Map.values()
    |> Enum.sum()
  end
})