Juha-Matti Santala
Community Builder. Dreamer. Adventurer.

Advent of Code - 2021

This is a solution to Day 13 of Advent of Code 2021.

Day 13 - Transparent Origami

You reach another volcanically active part of the cave. It would be nice if you could do some kind of thermal imaging so you could tell ahead of time which caves are too hot to safely enter.

Fortunately, the submarine seems to be equipped with a thermal camera! When you activate it, you are greeted with:

Congratulations on your purchase! To activate this infrared thermal imaging
camera system, please enter the code found on page 1 of the manual.

Apparently, the Elves have never used this feature. To your surprise, you manage to find the manual; as you go to open it, page 1 falls out. It's a large sheet of transparent paper! The transparent paper is marked with random dots and includes instructions on how to fold it up (your puzzle input). For example:

6,10
0,14
9,10
0,3
10,4
4,11
6,0
6,12
4,1
0,13
10,12
3,4
3,0
8,4
1,10
2,14
8,10
9,0
fold along y=7
fold along x=5

The first section is a list of dots on the transparent paper. 0,0 represents the top-left coordinate. The first value, x, increases to the right. The second value, y, increases downward. So, the coordinate 3,0 is to the right of 0,0, and the coordinate 0,7 is below 0,0. The coordinates in this example form the following pattern, where # is a dot on the paper and . is an empty, unmarked position:

...#..#..#.
....#......
...........
#..........
...#....#.#
...........
...........
...........
...........
...........
.#....#.##.
....#......
......#...#
#..........
#.#........

Then, there is a list of fold instructions}. Each instruction indicates a line on the transparent paper and wants you to fold the paper up (for horizontal y=... lines) or left (for vertical x=... lines). In this example, the first fold instruction is fold along y=7, which designates the line formed by all of the positions where y is 7 (marked here with -):

...#..#..#.
....#......
...........
#..........
...#....#.#
...........
...........
​-----------
...........
...........
.#....#.##.
....#......
......#...#
#..........
#.#........

Because this is a horizontal line, fold the bottom half up. Some of the dots might end up overlapping after the fold is complete, but dots will never appear exactly on a fold line. The result of doing this fold looks like this:

#.##..#..#.
#...#......
......#...#
#...#......
.#.#..#.###
...........
...........

Now, only 17 dots are visible.

Notice, for example, the two dots in the bottom left corner before the transparent paper is folded; after the fold is complete, those dots appear in the top left corner (at 0,0 and 0,1). Because the paper is transparent, the dot just below them in the result (at 0,3) remains visible, as it can be seen through the transparent paper.

Also notice that some dots can end up overlapping; in this case, the dots merge together and become a single dot.

The second fold instruction is fold along x=5, which indicates this line:

#.##.|#..#.
#...#|.....
.....|#...#
#...#|.....
.#.#.|#.###
.....|.....
.....|.....

Because this is a vertical line, fold left:

#####
#...#
#...#
#...#
#####
.....
.....

The instructions made a square!

The transparent paper is pretty big, so for now, focus on just completing the first fold. After the first fold in the example above, 17 dots are visible - dots that end up overlapping after the fold is completed count as a single dot.

Read input

Today we have a unique two-part input so we need a custom parser.

Update after Day 14:

I created a new read_multisection_input function to keep things in better shape.

from utils import read_multisection_input

def coordinate_transformer(section):
    output = []
    for coordinate in section.split('\n'):
        x, y = coordinate.strip().split(',')
        output.append((int(x), int(y)))
    return output

def fold_instruction_transformer(section):
    output = []
    for instruction in section.split('\n'):
        _, location = instruction.strip().split('fold along ')
        axis, row = location.split('=')
        row = int(row)
        output.append((axis, row))
    return output

f_coordinates, f_folds = read_multisection_input(
        13, 
        [coordinate_transformer, 
        fold_instruction_transformer]
)

This puzzle is simpler than it feels. The coordinate system as a whole doesn't really matter: the only thing that matters is individual position in relation to the fold.

So we can pretty much ignore that there is any kind of coordinate system.

For each point (coordinate since we don't keep track of empty locations) we calculate its distance to the fold.

If it's on the top or left side of the fold (delta being negative), we don't change anything.
If it's on the bottom or right side of the fold, we calculate the new x/y coordinate based on which fold we are performing.

To manage overlaps, I use set for the new coordinates so I don't have to think about overlaps at all.

def make_fold(coordinates, fold_line):
    new_coords = set()
    index = 0 if fold_line[0] == 'x' else 1
    for coordinate in coordinates:
        # Calculate the distance from fold line to our value
        delta = coordinate[index] - fold_line[1]
        
        if delta < 0: # On the top/left side of fold, no change
            new_coords.add(coordinate)
            continue
            
        if index == 0:
            new_x = abs(fold_line[1] - delta)
            new_coords.add((new_x, coordinate[1]))
        else:
            new_y = abs(fold_line[1] - delta)
            new_coords.add((coordinate[0], new_y))
            
    return new_coords

How many dots are visible after completing just the first fold instruction on your transparent paper?

new_plane = make_fold(coordinates, folds[0])
result = len(new_plane)
print(f'Solution: {result}')
assert result == 724

Solution: 724

Part 2

90% of my time today went to debugging my debug/part2 printer function.

Well, to be honest, I thought the problems were in my make_fold function but all the bugs turned out to be in this.

Here we print out '#' for each coordinate that has a point and a character defined by empty parameter if it's not. The reason I used empty here is because it was easier to debug against the example using . but easier to read out the code with empty string.

First problem I had here was I was printing x and y in different order (hence I refactored to row and column to make it easier to keep track, and the second problem was I had a off-by-one error at my range functions.

def print_coords(coordinates, empty=' '):
    max_cols = max(c[0] for c in coordinates)
    max_rows = max(c[1] for c in coordinates)
    for row in range(max_rows + 1):
        for col in range(max_cols + 1):
            if (col, row) in coordinates:
                print('#', end="")
            else:
                print(empty, end="")
        print()

Finish folding the transparent paper according to the instructions. The manual says the code is always eight capital letters.

What code do you use to activate the infrared thermal imaging camera system?

Here I was so worried I had to somehow calculate which letters the output presented but then I realized that I can just read it as a human from the screen which trivialized the second part since my first part already had everything working.

We make all the folds and then print out the result.

I made a temporary coords helper variable here since coords = make_fold(...) changes the original and I didn't want to end up in a situation where I run it twice with coordinates = make_fold(...) only to keep folding over something that had already folded. This is a recurring issue with Advent of Code puzzles.

coords = set(coordinates)
for fold in folds:
    coords = make_fold(coords, fold)
    
print_coords(coords)
## Should print something that looks like CPJBERUL
     ##  ###    ## ###  #### ###  #  # #
    #  # #  #    # #  # #    #  # #  # #
    #    #  #    # ###  ###  #  # #  # #
    #    ###     # #  # #    ###  #  # #
    #  # #    #  # #  # #    # #  #  # #
     ##  #     ##  ###  #### #  #  ##  ####