Powered by AppSignal & Oban Pro

Advent of Code 2023 - Day 04

2023/04.livemd

Advent of Code 2023 - Day 04

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

Input

{:ok, puzzle_input} =
  KinoAOC.download_puzzle("2023", "4", System.fetch_env!("LB_AOC_SESSION"))
split = fn input -> String.split(input, " ", trim: true) end

match_counts =
  puzzle_input
  |> String.split("\n")
  |> Stream.map(fn line -> String.split(line, [": ", " | "]) end)
  |> Stream.map(fn [_card, left, right] -> {split.(left), split.(right)} end)
  |> Stream.map(fn {winners, numbers} -> winners -- winners -- numbers end)
  |> Stream.map(fn matches -> Enum.count(matches) end)
  |> Enum.with_index(1)

Part 1

match_counts
|> Stream.filter(fn {count, _} -> count > 0 end)
|> Stream.map(fn {count, _} -> Integer.pow(2, count - 1) end)
|> Enum.sum()

Part 2

for {count, i} <- match_counts,
    count > 0,
    j <- (i + 1)..(i + count),
    reduce: Map.new(match_counts, fn {_, i} -> {i, 1} end) do
  acc -> Map.put(acc, j, acc[j] + acc[i])
end
|> Map.values()
|> Enum.sum()

Run in Livebook