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

Advent of Code 2023 - Day 09

2023/09.livemd

Advent of Code 2023 - Day 09

Mix.install([
  {:kino, "~> 0.11.0"},
  {:kino_aoc, github: "ljgago/kino_aoc"}
])

Input

{:ok, puzzle_input} =
  KinoAOC.download_puzzle("2023", "9", System.fetch_env!("LB_AOC_SESSION"))
history =
  puzzle_input
  |> String.split("\n", trim: true)
  |> Enum.map(fn line ->
    String.split(line, " ", trim: true)
    |> Enum.map(&String.to_integer(&1))
  end)

Part 1

extrapolate = fn input, map_fun, reduce_fun ->
  Stream.map(input, fn h ->
    Stream.unfold(h, fn row ->
      next_row =
        for i <- 1..(Enum.count(row) - 1) do
          Enum.at(row, i) - Enum.at(row, i - 1)
        end

      unless Enum.all?(row, &amp;(&amp;1 == 0)), do: {map_fun.(row), next_row}
    end)
    |> Enum.reverse()
    |> Enum.reduce(0, reduce_fun)
  end)
end

history
|> extrapolate.(&amp;List.last/1, &amp;+/2)
|> Enum.sum()

Part 2

history
|> extrapolate.(&amp;List.first/1, &amp;-/2)
|> Enum.sum()

Run in Livebook