August 18, 2023

Solution for Advent of Code 2015 - Day 3: Perfectly Spherical Houses in a Vacuum

For this puzzle, we need to figure out which houses are visited by santa based on a move list. Since the number of moves is small, we can simulate every step. For tracking the current (x,y) position, we could use a 2D-array, but we use a complex number (x+iy) instead. If we want to move into x direction, we add or subtract to the real part, while moves in y direction change the imaginary part of the number. For this puzzle it is not really necessary, but it can simplify future 2D handling.

Here is the main function handling the moves. We track the visited positions in a set to get rid of duplicates and initialise with 0 as the start position.

def move(movelist):
visited_pos = {0}

pos = 0 + 0j
for i, char in enumerate(movelist):
next_move = {"^": 1j, "v": -1j, "<": -1, ">": 1}[char]
pos += next_move
visited_pos.add(pos)

return len(visited_pos)

Again this was tested against the supplied inputs and was correct on my input.

Part 2

In part 2, we have two santas moving across the board with each move alternating between the two. The movelist will now consists of (move of  santa 1), (move of  santa 2), (move of  santa 1), . Since the moves do no interact, we can split the movelist beforehand into two and reduce the problem to the same function as before.

def move(movelist, num_santas):
visited_pos = {0}

for i in range(num_santas):
specific_move_list = movelist[i::num_santas]
pos = 0 + 0j
for char in specific_move_list:
next_move = {"^": 1j, "v": -1j, "<": -1, ">": 1}[char]
pos += next_move
visited_pos.add(pos)

return len(visited_pos)

Here I modified the function from before to include the number of santas. For part 1, this was set to 1. The other differences are the splitting of the input into seperate move lists via python list expressions and the outer loop over all santas. Both santas add to the same visited_pos set, since we only care about positions visited by at least one of them.

Since I modified the original function, I again checked the solutions for part 1 in addition to the part 2 input.

Link to my solutions

No comments:

Post a Comment