🎄⌨️ Advent of Code 2018

Tech-note 541fa8

I was pretty happy with my conceptual approach to this one.

;; I define a DIRECTION in terms of its effect on the x,y coordinates.
;; And a COMPASS is a list of DIRECTIONs, with current direction in 1st position.
;; Rotate the list one way or the other == turning direction.
;; Listed here starting with UP, moving counter-clockwise
(define cardinal-directions '((0 -1) (-1 0) (0 1) (1 0)))

So, considering cardinal-directions above as a compass, the first element is (0 -1), meaning a move in that direction would add 0 to the x coordinate and -1 to the y coordinate — in other words, a move “up” on the map.

And you can “turn” simply by shift-cycling the compass one way or the other:

❯ (shift-cycle-left cardinal-directions 1)
'((-1 0) (0 1) (1 0) (0 -1))    ; Compass is now pointing LEFT

I was able to get the location of the first collision pretty easily, but I was stymied for a couple days on the solution to part 2. I ended up writing a lot of instrumentation to try and get some insight into what was going wrong.

Here’s what it came down to:

--+-+++---+--
--+-+++---+--
--+-++v---+--
--+-++<---+--
  | ||^   |  
--+-+++---+--
--+-+++---+--

This is a cropped view of the situation at the 919th tick in my input. You may dimly discern three carts adjacent to each other. The correct outcome is for the topmost cart to move first and collide with the middle one; those two colliding cars are instantly removed; and finally the surviving bottom car moves up into the spot where the collision happened and continues on its way.

I was initially getting the wrong outcome for two reasons: one, I didn’t read closely enough at first and assumed it was possible for more than two cars to collide during the same tick. Second, I had a mistake in the comparison function I wrote that is used to sort the carts and ensure they are moved in the correct order. So the wrong cart was surviving this situation, changing the entire outcome.