Advent of Code day 11

Advent of Code day 11

In Today's puzzle we want to find a good seat on the ferry to vacationland.

Time to break out the np.arrays!

This problem can be done with lists of lists, but I want to brush up on np.arrays and it may be helpful to have this more robust solution for part 2.

To create a numpy array from a list of lists you just:

floor_plan = np.array(floor_plan)

Then you can subscript floor_plan using

floor_plan[i][j]

Back to the problem -- we can now step through the seats and for each seat, check the surrounding seats. To simplify our logic, we’ll put a row of floor all round the outside of the seating area. Then we don’t need special cases for corners and edges. (We can step through from floor_plan[1][1] to floor_plan[max_i - 1][max_j - 1])

Numpy has a nice option to pad an array:

x = np.pad(x, pad_width=1, mode='constant', constant_values=0)

So we write a couple loops to step through the seats and at each seat we call a function to check the surrounding seats. A bit of fiddling to get the array dimensions right and sort out our columns and rows, and we have something that works. One star.

In Part 2 we find that we need to actually look along the loops and diagonals to find the first seat that can be seen from each seat. This adds a bit of complexity, but it's not too bad. I did run into trouble because I had an embedded loop to count through the rows and columns and that doesn’t do a diagonal -- I needed to count through them simultaneously.

So, instead of this:

   for ii in i_up:
         for jj in j_up:
             ... logic to check seats

(where i_up and j_up are the range of seat locations) which goes through a full rectangle of seats.

I needed to do:

   for ii, jj in zip(i_up, j_up):
        ... logic to check seats

Today (the 12th) I completed the day's puzzle pretty quickly and revisited this one. My solution is pretty long, and I was able to streamline it a bit. Then I checked reddit and found some amazing short solutions, but also several that looked like mine. I want to piece through the shorter ones and I'd like to make my code run faster (each part takes about 6 seconds at the moment), but that will have to wait until another day.

I recommend checking out the reddit solution megathreads once you've completed the puzzle, or if you get really stuck. It's useful to look at other people solutions -- I always learn something. That link is here: https://www.reddit.com/r/adventofcode/wiki/solution_megathreads.

People also post some really nice animations of the solutions, like:

My solution is on Github.