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

Advent of Code 2023 - Day 02

2023/day02.livemd

Advent of Code 2023 - Day 02

Mix.install([:kino_aoc])

Input

{:ok, puzzle_input} =
  KinoAOC.download_puzzle("2023", "2", System.fetch_env!("LB_AOC_SESSION"))
test_input = """
Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green
Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue
Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red
Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red
Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green
"""
input_field =
  Kino.Input.select("input", [
    {test_input, "Test Input"},
    {puzzle_input, "Puzzle Input"}
  ])

Parse

parsed =
  input_field
  |> Kino.Input.read()
  |> String.split("\n", trim: true)
  |> Enum.map(&String.split(&1, ~w(: ; ,), trim: true))
  |> Enum.map(fn [game | cubes] ->
    gamenr =
      game
      |> String.replace_prefix("Game ", "")
      |> String.to_integer()

    cubes =
      cubes
      |> Enum.map(fn cube -> String.split(cube, " ", trim: true) end)
      |> Enum.map(fn [amount, color] -> {String.to_atom(color), String.to_integer(amount)} end)
      |> Enum.group_by(&elem(&1, 0), &elem(&1, 1))
      |> Map.new(fn {color, amounts} -> {color, Enum.max(amounts)} end)

    {gamenr, cubes}
  end)

Part 1

parsed
|> Enum.reject(fn {_game, cubes} ->
  cubes.red > 12 or cubes.green > 13 or cubes.blue > 14
end)
|> Enum.map(&elem(&1, 0))
|> Enum.sum()

Part 2

parsed
|> Enum.map(fn {_game, cubes} -> Map.values(cubes) end)
|> Enum.map(&Enum.product/1)
|> Enum.sum()