Juha-Matti Santala

# Advent of Code - 2023

This is a solution to Day 16 of Advent of Code 2023.

# Day 16: The Floor Will Be Lava

With the beam of light completely focused somewhere, the reindeer leads you deeper still into the Lava Production Facility. At some point, you realize that the steel facility walls have been replaced with cave, and the doorways are just cave, and the floor is cave, and you're pretty sure this is actually just a giant cave.

Finally, as you approach what must be the heart of the mountain, you see a bright light in a cavern up ahead. There, you discover that the beam of light you so carefully focused is emerging from the cavern wall closest to the facility and pouring all of its energy into a contraption on the opposite side.

Upon closer inspection, the contraption appears to be a flat, two-dimensional square grid containing empty space (.), mirrors (/ and ), and splitters (| and -).

The contraption is aligned so that most of the beam bounces around the grid, but each tile on the grid converts some of the beam's light into heat to melt the rock in the cavern.

You note the layout of the contraption (your puzzle input). For example:

``````.|...\....
|.-.\.....
.....|-...
........|.
..........
.........\
..../.\\..
.-.-/..|..
.|....-|.\
..//.|....
``````

The beam enters in the top-left corner from the left and heading to the right. Then, its behavior depends on what it encounters as it moves:

• If the beam encounters empty space (.), it continues in the same direction.
• If the beam encounters a mirror (/ or ), the beam is reflected 90 degrees depending on the angle of the mirror. For instance, a rightward-moving beam that encounters a / mirror would continue upward in the mirror's column, while a rightward-moving beam that encounters a \ mirror would continue downward from the mirror's column.
• If the beam encounters the pointy end of a splitter (| or -), the beam passes through the splitter as if the splitter were empty space. For instance, a rightward-moving beam that encounters a - splitter would continue in the same direction.
• If the beam encounters the flat side of a splitter (| or -), the beam is split into two beams going in each of the two directions the splitter's pointy ends are pointing. For instance, a rightward-moving beam that encounters a | splitter would split into two beams: one that continues upward from the splitter's column and one that continues downward from the splitter's column.

Beams do not interact with other beams; a tile can have many beams passing through it at the same time. A tile is energized if that tile has at least one beam pass through it, reflect in it, or split in it.

In the above example, here is how the beam of light bounces around the contraption:

``````>|<<<\....
|v-.\^....
.v...|->>>
.v...v^.|.
.v...v^...
.v...v^..\
.v../2\\..
<->-/vv|..
.|<<<2-|.\
.v//.|.v..
``````

Beams are only shown on empty tiles; arrows indicate the direction of the beams. If a tile contains beams moving in multiple directions, the number of distinct directions is shown instead. Here is the same diagram but instead only showing whether a tile is energized (#) or not (.):

``````######....
.#...#....
.#...#####
.#...##...
.#...##...
.#...##...
.#..####..
########..
.#######..
.#...#.#..
``````

Ultimately, in this example, 46 tiles become energized.

The light isn't energizing enough tiles to produce lava; to debug the contraption, you need to start by analyzing the current situation. With the beam starting in the top-left heading right, how many tiles end up being energized?

I don't know if it's a recency bias or what but I feel like there's been a lot of grid based puzzles this year and I'm having a bit of tournament fatigue with them.

Today's one was not the toughest though for me. I made a silly mistake that slowed down the execution a ton (by a magnitude of ~1000) but other than that, got through on the second try. I also didn't realize at the beginning that there can be loops that need to be detected.

I read the input into a dictionary with Complex Number Coordinate System (where `(x,y)` maps to `x + y*1j`).

``````from utils import read_input

def make_grid(inp):
grid = {}
for y, row in enumerate(inp):
for x, cell in enumerate(row):
grid[x + y * -1j] = cell
return grid

``````

To help out with readability, I have to helper classes with constants for different grid elements and directions.

``````class Grid:
EMPTY = '.'
VERTICAL_SPLITTER = '|'
HORIZONTAL_SPLITTER = '-'
FORWARD_MIRROR = '/'
BACKWARD_MIRROR = '\\'

class Direction:
RIGHT = 1
LEFT = -1
UP = 1j
DOWN = -1j
``````

The main solution is a recursive function that follows the path of the beam.

It's base cases are if we run out of the grid or we run into a loop (which is identified by a coordinate + direction combo being tracked). In these cases, we return the set of all visited coordinate + direction combos.

Otherwise, we add our current coordinate + direction to the collection and then use Python's pattern matching to match our current location's content and direction to see where we move next.

I really like how clean and readable the pattern match combined with our helper constant classes make this function.

``````def energize(grid, current, energized, direction):
if current not in grid:
return energized
if (current, direction) in energized:
return energized

match grid[current]:
case Grid.EMPTY:
return energize(grid, current + direction, energized, direction)
case Grid.FORWARD_MIRROR:
match direction:
case Direction.RIGHT:
return energize(grid, current + Direction.UP, energized, Direction.UP)
case Direction.DOWN:
return energize(grid, current + Direction.LEFT, energized, Direction.LEFT)
case Direction.LEFT:
return energize(grid, current + Direction.DOWN, energized, Direction.DOWN)
case Direction.UP:
return energize(grid, current + Direction.RIGHT, energized, Direction.RIGHT)
case _:
raise ValueError('Unknown direction')
case Grid.BACKWARD_MIRROR:
match direction:
case Direction.RIGHT:
return energize(grid, current + Direction.DOWN, energized, Direction.DOWN)
case Direction.DOWN:
return energize(grid, current + Direction.RIGHT, energized, Direction.RIGHT)
case Direction.LEFT:
return energize(grid, current + Direction.UP, energized, Direction.UP)
case Direction.UP:
return energize(grid, current + Direction.LEFT, energized, Direction.LEFT)
case _:
raise ValueError('Unknown direction')
case Grid.VERTICAL_SPLITTER:
match direction:
case Direction.UP | Direction.DOWN:
return energize(grid, current + direction, energized, direction)
case Direction.LEFT | Direction.RIGHT:
return (
energize(grid, current + Direction.UP, energized, Direction.UP) |
energize(grid, current + Direction.DOWN, energized, Direction.DOWN)
)
case _:
raise ValueError('Unknown direction')
case Grid.HORIZONTAL_SPLITTER:
match direction:
case Direction.RIGHT | Direction.LEFT:
return energize(grid, current + direction, energized, direction)
case Direction.UP | Direction.DOWN:
return (
energize(grid, current + Direction.RIGHT, energized, Direction.RIGHT) |
energize(grid, current + Direction.LEFT, energized, Direction.LEFT)
)
case _:
raise ValueError('Unknown direction')
case _:
raise ValueError('Unknown title')
``````

To calculate the number of energized tiles, I put all the coordinates in a set and return its length.

``````def count_energized_tiles(energized):
return len(set(coord for (coord, direction) in energized))
``````
``````energized_grid = energize(grid, 0, set(), 1)
part_1 = count_energized_tiles(energized_grid)

print(f'Solution: {part_1}')
assert part_1 == 7210
``````

Solution: 7210

## Part 2

As you try to work out what might be wrong, the reindeer tugs on your shirt and leads you to a nearby control panel. There, a collection of buttons lets you align the contraption so that the beam enters from any edge tile and heading away from that edge. (You can choose either of two directions for the beam if it starts on a corner; for instance, if the beam starts in the bottom-right corner, it can start heading either left or upward.)

So, the beam could start on any tile in the top row (heading downward), any tile in the bottom row (heading upward), any tile in the leftmost column (heading right), or any tile in the rightmost column (heading left). To produce lava, you need to find the configuration that energizes as many tiles as possible.

In the above example, this can be achieved by starting the beam in the fourth tile from the left in the top row:

``````.|<2<\....
|v-v\^....
.v.v.|->>>
.v.v.v^.|.
.v.v.v^...
.v.v.v^..\
.v.v/2\\..
<-2-/vv|..
.|<<<2-|.\
.v//.|.v..
``````

Using this configuration, 51 tiles are energized:

``````.#####....
.#.#.#....
.#.#.#####
.#.#.##...
.#.#.##...
.#.#.##...
.#.#####..
########..
.#######..
.#...#.#..
``````

Find the initial beam configuration that energizes the largest number of tiles; how many tiles are energized in that configuration?

For the second part, I generate all the possible starting coordinates with their accompanied starting directions.

``````def generate_start_coords(grid):
min_x = 0
max_x = int(max(coord.real for coord in grid))
min_y = int(min(coord.imag for coord in grid))
max_y = 0

top_row = [(x, Direction.DOWN) for x in range(min_x, max_x+1)]
bottom_row = [(x + min_y*1j, Direction.UP) for x in range(min_x, max_x+1)]

left_column = [(y*1j, Direction.RIGHT) for y in range(min_y, max_y+1)]
right_column = [(max_x + y*1j, Direction.LEFT) for y in range(min_y, max_y+1)]

``````

The longest beam had more steps than the default recursion limit so I had to bump it up a bit before trying every starting position and keeping track of the largest one.

This is not a particularly fast solution. With different data structures, I could probably memoize the different beam movements, making it way faster.

``````import sys
sys.setrecursionlimit(30000)

most_energized = 0
for coord, direction in generate_start_coords(grid):
energized = count_energized_tiles(energize(grid, coord, set(), direction))
most_energized = max(energized, most_energized)

print(f'Solution: {most_energized}')
assert most_energized == 7673
``````

Solution: 7673

32 stars!