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

Day11

11.livemd

Day11

Section

example = "125 17"
input = "9759 0 256219 60 1175776 113 6 92833"

defmodule Day11 do
  def solve(input, target_depth) do
    line =
      input
      |> String.split(" ", trim: true)
      |> Enum.map(&String.to_integer/1)
      |> Enum.map(&{&1, 0})

    {acc, _cache} = blink(line, %{}, target_depth, 0)
    acc
  end

  def blink([], cache, _, acc) do
    {acc, cache}
  end

  def blink([{h, depth} | t], cache, target_depth, acc) do
    cond do
      depth == target_depth ->
        blink(t, cache, target_depth, acc + 1)

      h == 0 ->
        blink([{1, depth + 1} | t], cache, target_depth, acc)

      rem(len = String.length(sh = to_string(h)), 2) == 0 ->
        if sum = Map.get(cache, {h, depth}) do
          blink(t, cache, target_depth, sum + acc)
        else
          {slh, srh} = String.split_at(sh, div(len, 2))
          lh = String.to_integer(slh)
          rh = String.to_integer(srh)

          {sum, cache} = blink([{lh, depth + 1}, {rh, depth + 1}], cache, target_depth, 0)
          cache = Map.put(cache, {h, depth}, sum)

          blink(t, cache, target_depth, sum + acc)
        end

      true ->
        blink([{h * 2024, depth + 1} | t], cache, target_depth, acc)
    end
  end
end

IO.inspect(Day11.solve(input, 25), label: "Part 1")
IO.inspect(Day11.solve(input, 75), label: "Part 2")