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

Advent of Code 2023

day1.livemd

Advent of Code 2023

Mix.install([
  {:kino, "~> 0.14.1"}
])

Day 1

input = Kino.Input.textarea("")
# 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 = input
|> Kino.Input.read()

config = %{
  "red" => 12,
  "green" => 13,
  "blue" => 14
}
# PART 1

input
|> String.split("\n", trim: true)
|> Enum.map(fn game ->
  [game_id, sets] = String.split(game, ": ")
  id = String.replace(game_id, "Game ", "") |> String.to_integer()
  sets = sets
  |> String.split("; ")
  |> Enum.map(fn set ->
    set
    |> String.split(", ")
    |> Enum.map(fn cube ->
      [count, color] = String.split(cube, " ")
      {String.to_atom(color), String.to_integer(count)}
    end)
    |> Enum.into(%{})
  end)
  {id, sets}
end)
|> Enum.filter(fn {_id, sets} ->
  Enum.all?(sets, fn set ->
    Map.get(set, :red, 0) <= 12 &amp;&amp;
    Map.get(set, :green, 0) <= 13 &amp;&amp;
    Map.get(set, :blue, 0) <= 14
  end)
end)
|> Enum.map(fn {id, _sets} -> id end)
|> Enum.sum()
# PART 2

input
|> String.split("\n", trim: true)
|> Enum.map(fn game ->
  [_game_id, sets] = String.split(game, ": ")
  sets
  |> String.split("; ")
  |> Enum.flat_map(fn set ->
    set
    |> String.split(", ")
    |> Enum.map(fn cube ->
      [count, color] = String.split(cube, " ")
      {String.to_atom(color), String.to_integer(count)}
    end)
  end)
  |> Enum.group_by(
    fn {color, _} -> color end,
    fn {_, count} -> count end
  )
  |> Map.new(fn {color, counts} -> {color, Enum.max(counts)} end)
  |> Map.values()
  |> Enum.product()
end)
|> Enum.sum()