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

Day 2

Day2.livemd

Day 2

Mix.install([
  {:kino_aoc, "~> 0.1.5"}
])

Input

{:ok, puzzle_input} =
  KinoAOC.download_puzzle("2023", "2", System.fetch_env!("LB_AOC_SESSION"))
lines = String.split(puzzle_input, "\n")

games =
  Enum.map(lines, fn line ->
    line
    |> String.split(": ")
    |> Enum.at(1)
    |> String.split("; ")
    |> Enum.map(fn s ->
      String.split(s, ", ")
      |> Enum.map(fn x ->
        [n, c] = String.split(x)
        {String.to_atom(c), String.to_integer(n)}
      end)
      |> Map.new()
    end)
  end)

Part 1

limits = %{red: 12, green: 13, blue: 14}

games
|> Enum.with_index(1)
|> Enum.filter(fn {g, _i} ->
  Enum.all?(g, fn d ->
    Enum.all?(d, fn {c, n} ->
      n <= limits[c]
    end)
  end)
end)
|> Enum.map(&amp;elem(&amp;1, 1))
|> Enum.sum()

Part 2

games
|> Enum.map(fn g ->
  g
  |> Enum.reduce(&amp;Map.merge(&amp;1, &amp;2, fn _k, v1, v2 -> max(v1, v2) end))
  |> Enum.map(&amp;elem(&amp;1, 1))
  |> Enum.reduce(&amp;(&amp;1 * &amp;2))
end)
|> Enum.sum()