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

Advent of Code 2015 Day 6 Part 2

2015_day6_part2.livemd

Advent of Code 2015 Day 6 Part 2

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

Get Inputs

{:ok, puzzle_input} =
  KinoAOC.download_puzzle("2015", "6", System.fetch_env!("LB_SESSION"))

My answer

puzzle_input
|> String.split("\n")
|> Enum.reduce(%{},fn instruction, map ->
  %{"op" => op, "sx" => sx, "sy" => sy, "ex" => ex, "ey" => ey} =
    Regex.named_captures(
      ~r/(?.+) (?\d+),(?\d+) through (?\d+),(?\d+)/,
      instruction
    )

  [sx, sy, ex, ey] = Enum.map([sx, sy, ex, ey], &String.to_integer(&1))

  Enum.reduce(sx..ex, map, fn x, x_map ->
    Enum.reduce(sy..ey, x_map, fn y, y_map ->
      brightness = Map.get(y_map, {x, y}, 0)

      brightness =
        case op do
          "turn on" -> brightness + 1
          "turn off" -> max(0, brightness - 1)
          _ -> brightness + 2
        end

      Map.put(y_map, {x, y}, brightness)
    end)
  end)
end)
|> Enum.map(fn {_, brightness} -> brightness end)
|> Enum.sum()