Skip to content
advent of code 2020

day 12

rain risk

approach

each instruction is a letter and a number. the ship keeps a position and a direction vector (dx, dy). N/S/E/W move the position directly, L/R rotate the direction vector with a rotation matrix (cos and sin of the angle in radians), and F moves along the vector. part 1 starts facing east, (1, 0), and answers with the manhattan distance from the origin.

part 2 reuses the same loop almost line for line, but the vector is now a waypoint starting at (10, 1): the compass letters move the waypoint instead of the ship, and F moves the ship by the waypoint n times.

the trick

treat the heading and the waypoint as the same thing, a vector you rotate and walk along.

python
def rotate(px, py, rad):
    ca = cos(rad)
    sa = sin(rad)
    return ca * px - sa * py, sa * px + ca * py