Skip to content
advent of code 2022

day 09

rope bridge

approach

the rope is a list of [r, c] knots. each step moves the head one cell, then every following knot catches up with the one in front: if they're more than one cell apart, it moves one step towards it on each axis using the sign of the difference. the tail's positions go into a set, and its size is the answer. simulate does this for any number of knots, so part 1 uses 2 and part 2 uses 10.

as committed, the script doesn't print either answer: the simulate call is commented out and it runs animation instead, which draws the 10-knot rope in the terminal with curses after every move and discards the count.

the trick

a knot that falls behind moves by the sign of the gap on each axis, which covers straight and diagonal moves at once.

python
def follow(fl, ft):
    dr = fl[0] - ft[0]
    dc = fl[1] - ft[1]

    if abs(dr) <= 1 and abs(dc) <= 1:
        return

    ft[0] += sign(dr)
    ft[1] += sign(dc)