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

Advent of Code 2023 - Day 14

2023/elixir/livebooks/day14.livemd

Advent of Code 2023 - Day 14

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

Introduction

— Day 14: Parabolic Reflector Dish —

You reach the place where all of the mirrors were pointing: a massive parabolic reflector dish attached to the side of another large mountain.

The dish is made up of many small mirrors, but while the mirrors themselves are roughly in the shape of a parabolic reflector dish, each individual mirror seems to be pointing in slightly the wrong direction. If the dish is meant to focus light, all it’s doing right now is sending it in a vague direction.

This system must be what provides the energy for the lava! If you focus the reflector dish, maybe you can go where it’s pointing and use the light to fix the lava production.

Upon closer inspection, the individual mirrors each appear to be connected via an elaborate system of ropes and pulleys to a large metal platform below the dish. The platform is covered in large rocks of various shapes. Depending on their position, the weight of the rocks deforms the platform, and the shape of the platform controls which ropes move and ultimately the focus of the dish.

In short: if you move the rocks, you can focus the dish. The platform even has a control panel on the side that lets you tilt it in one of four directions! The rounded rocks (O) will roll when the platform is tilted, while the cube-shaped rocks (#) will stay in place. You note the positions of all of the empty spaces (.) and rocks (your puzzle input). For example:

O....#....
O.OO#....#
.....##...
OO.#O....O
.O.....O#.
O.#..O.#.#
..O..#O..O
.......O..
#....###..
#OO..#....

Start by tilting the lever so all of the rocks will slide north as far as they will go:

OOOO.#.O..
OO..#....#
OO..O##..O
O..#.OO...
........#.
..#....#.#
..O..#.O.O
..O.......
#....###..
#....#....

You notice that the support beams along the north side of the platform are damaged; to ensure the platform doesn’t collapse, you should calculate the total load on the north support beams.

The amount of load caused by a single rounded rock (O) is equal to the number of rows from the rock to the south edge of the platform, including the row the rock is on. (Cube-shaped rocks (#) don’t contribute to load.) So, the amount of load caused by each rock in each row is as follows:

OOOO.#.O.. 10
OO..#....#  9
OO..O##..O  8
O..#.OO...  7
........#.  6
..#....#.#  5
..O..#.O.O  4
..O.......  3
#....###..  2
#....#....  1

The total load is the sum of the load caused by all of the rounded rocks. In this example, the total load is 136.

Tilt the platform so that the rounded rocks all roll north. Afterward, what is the total load on the north support beams?

— Part Two —

The parabolic reflector dish deforms, but not in a way that focuses the beam. To do that, you’ll need to move the rocks to the edges of the platform. Fortunately, a button on the side of the control panel labeled “spin cycle” attempts to do just that!

Each cycle tilts the platform four times so that the rounded rocks roll north, then west, then south, then east. After each tilt, the rounded rocks roll as far as they can before the platform tilts in the next direction. After one cycle, the platform will have finished rolling the rounded rocks in those four directions in that order.

Here’s what happens in the example above after each of the first few cycles:

After 1 cycle:
.....#....
....#...O#
...OO##...
.OO#......
.....OOO#.
.O#...O#.#
....O#....
......OOOO
#...O###..
#..OO#....

After 2 cycles:
.....#....
....#...O#
.....##...
..O#......
.....OOO#.
.O#...O#.#
....O#...O
.......OOO
#..OO###..
#.OOO#...O

After 3 cycles:
.....#....
....#...O#
.....##...
..O#......
.....OOO#.
.O#...O#.#
....O#...O
.......OOO
#...O###.O
#.OOO#...O

This process should work if you leave it running long enough, but you’re still worried about the north support beams. To make sure they’ll survive for a while, you need to calculate the total load on the north support beams after 1000000000 cycles.

In the above example, after 1000000000 cycles, the total load on the north support beams is 64.

Run the spin cycle for 1000000000 cycles. Afterward, what is the total load on the north support beams?

Puzzle

{:ok, puzzle_input} =
  KinoAOC.download_puzzle("2023", "14", System.fetch_env!("LB_AOC_SESSION"))
IO.puts(puzzle_input)

Tools

Code - Tools

defmodule Tools do
  def get_size(matrix) do
    size_x = matrix |> hd() |> length()
    size_y = matrix |> length()

    {size_x, size_y}
  end

  def get_value(matrix, {x, y}) do
    {size_x, size_y} = get_size(matrix)

    cond do
      x < 0 or x >= size_x ->
        "."

      y < 0 or y >= size_y ->
        "."

      true ->
        matrix
        |> Enum.at(y, [])
        |> Enum.at(x, ".")
    end
  end

  def transpose(matrix) do
    {size_x, size_y} = get_size(matrix)

    for x <- 0..(size_x - 1) do
      for y <- 0..(size_y - 1), into: [] do
        matrix
        |> Enum.at(y, [])
        |> Enum.at(x)
      end
    end
  end
end

Tests - Parser

ExUnit.start(autorun: false)

defmodule ParserTest do
  use ExUnit.Case, async: true
  # import Parser

  # @input ""
  # @expected nil

  # test "parse test" do
  #   assert parse(@input) == @expected
  # end
end

ExUnit.run()

Part One

Code - Part 1

defmodule PartOne do
  def solve(input) do
    IO.puts("--- Part One ---")
    IO.puts("Result: #{run(input)}")
  end

  def run(input) do
    matrix =
      input
      |> String.split("\n", trim: true)
      |> Enum.map(&amp;String.codepoints(&amp;1))

    matrix
    |> transpose()
    |> Enum.map(fn line ->
      line
      |> slice_by_cube()
      |> Enum.map(&amp;Enum.frequencies(&amp;1))
      |> Enum.map(fn frec ->
        String.duplicate("#", frec |> Map.get("#", 0)) <>
          String.duplicate("O", frec |> Map.get("O", 0)) <>
          String.duplicate(".", frec |> Map.get(".", 0))
      end)
      |> Enum.join()
      |> String.codepoints()
    end)
    |> transpose()
    |> Enum.with_index()
    |> Enum.map(fn {line, i} ->
      rounded_rocks =
        line
        |> Enum.frequencies()
        |> Map.get("O", 0)

      rounded_rocks * (length(matrix) - i)
    end)
    |> Enum.sum()
  end

  def slice_by_cube(arr) do
    for x <- 1..(length(arr) - 1), reduce: [0] do
      acc ->
        cond do
          Enum.at(arr, x - 1) == "#" and Enum.at(arr, x) == "#" ->
            acc

          Enum.at(arr, x) == "#" ->
            [x | acc]

          true ->
            acc
        end
    end
    |> List.insert_at(0, length(arr))
    |> Enum.reverse()
    |> Enum.chunk_every(2, 1, :discard)
    |> Enum.map(fn [x1, x2] -> Enum.slice(arr, x1, x2 - x1) end)
  end

  def transpose(matrix) do
    size_x = matrix |> hd() |> length()
    size_y = matrix |> length()

    for x <- 0..(size_x - 1) do
      for y <- 0..(size_y - 1) do
        matrix
        |> Enum.at(y, [])
        |> Enum.at(x)
      end
    end
  end
end

Tests - Part 1

ExUnit.start(autorun: false)

defmodule PartOneTest do
  use ExUnit.Case, async: true
  import PartOne

  @input """
  O....#....
  O.OO#....#
  .....##...
  OO.#O....O
  .O.....O#.
  O.#..O.#.#
  ..O..#O..O
  .......O..
  #....###..
  #OO..#....
  """
  @expected 136

  test "part one" do
    assert run(@input) == @expected
  end
end

ExUnit.run()

Solution - Part 1

PartOne.solve(puzzle_input)

Part Two

Code - Part 2

defmodule PartTwo do
  def solve(input, times) do
    IO.puts("--- Part Two ---")
    IO.puts("Result: #{run(input, times)}")
  end

  def run(input, times) do
    matrix =
      input
      |> String.split("\n", trim: true)
      |> Enum.map(&amp;String.codepoints(&amp;1))

    matrix
    |> iterate(times)
    |> Enum.with_index()
    |> Enum.map(fn {line, i} ->
      rounded_rocks =
        line
        |> Enum.frequencies()
        |> Map.get("O", 0)

      rounded_rocks * (length(matrix) - i)
    end)
    |> Enum.sum()
  end

  def spin_cycle(matrix, roll_direction) do
    matrix
    |> roll_direction.()
    |> Enum.map(fn line ->
      line
      |> slice_by_cube()
      |> Enum.map(&amp;Enum.frequencies(&amp;1))
      |> Enum.map(fn frec ->
        String.duplicate("#", frec |> Map.get("#", 0)) <>
          String.duplicate("O", frec |> Map.get("O", 0)) <>
          String.duplicate(".", frec |> Map.get(".", 0))
      end)
      |> Enum.join()
      |> String.codepoints()
    end)
    |> roll_direction.()
  end

  def slice_by_cube(arr) do
    for x <- 1..(length(arr) - 1), reduce: [0] do
      acc ->
        cond do
          Enum.at(arr, x - 1) == "#" and Enum.at(arr, x) == "#" ->
            acc

          Enum.at(arr, x) == "#" ->
            [x | acc]

          true ->
            acc
        end
    end
    |> List.insert_at(0, length(arr))
    |> Enum.reverse()
    |> Enum.chunk_every(2, 1, :discard)
    |> Enum.map(fn [x1, x2] -> Enum.slice(arr, x1, x2 - x1) end)
  end

  def roll_north(matrix) do
    size_x = matrix |> hd() |> length()
    size_y = matrix |> length()

    for x <- 0..(size_x - 1) do
      for y <- 0..(size_y - 1) do
        matrix
        |> Enum.at(y, [])
        |> Enum.at(x)
      end
    end
  end

  def roll_west(matrix), do: matrix

  def roll_south(matrix) do
    size_x = matrix |> hd() |> length()
    size_y = matrix |> length()

    for x <- (size_x - 1)..0 do
      for y <- (size_y - 1)..0 do
        matrix
        |> Enum.at(y, [])
        |> Enum.at(x)
      end
    end
  end

  def roll_east(matrix) do
    size_x = matrix |> hd() |> length()
    size_y = matrix |> length()

    for y <- 0..(size_y - 1) do
      for x <- (size_x - 1)..0 do
        matrix
        |> Enum.at(y, [])
        |> Enum.at(x)
      end
    end
  end

  def iterate(matrix, times), do: iterate(matrix, times, %{}, 0)
  def iterate(matrix, times, _, count) when count > times - 1, do: matrix

  def iterate(matrix, times, map, count) when is_map_key(map, matrix) do
    iterate(Map.get(map, matrix), times, map, count + 1)
  end

  def iterate(matrix, times, map, count) do
    new_matrix =
      matrix
      |> spin_cycle(&amp;roll_north/1)
      |> spin_cycle(&amp;roll_west/1)
      |> spin_cycle(&amp;roll_south/1)
      |> spin_cycle(&amp;roll_east/1)

    map =
      map
      |> Map.put_new(matrix, new_matrix)

    iterate(new_matrix, times, map, count + 1)
  end

  def fun1(n), do: fun1(n, 0)
  def fun1(n, acc) when acc >= n, do: n
  def fun1(n, acc), do: fun1(n, acc + 1)

  def fun2(n) do
    1..n
    |> Enum.reduce(0, fn _, acc ->
      acc + 1
    end)
  end
end
# PartTwo.fun1(1_000_000_000)
# PartTwo.fun2(1_000_000_000)
input =
  """
  O....#....
  O.OO#....#
  .....##...
  OO.#O....O
  .O.....O#.
  O.#..O.#.#
  ..O..#O..O
  .......O..
  #....###..
  #OO..#....
  """

PartTwo.run(input, 2)

Tests - Part 2

ExUnit.start(autorun: false)

defmodule PartTwoTest do
  use ExUnit.Case, async: true
  import PartTwo

  @input """
  O....#....
  O.OO#....#
  .....##...
  OO.#O....O
  .O.....O#.
  O.#..O.#.#
  ..O..#O..O
  .......O..
  #....###..
  #OO..#....
  """
  @expected 64

  test "part two" do
    assert run(@input, 1000) == @expected
  end
end

ExUnit.run()

Solution - Part 2

PartTwo.solve(puzzle_input, 1_000)