Skip to content
advent of code 2021

day 18

snailfish

approach

each snailfish number is parsed into a binary tree whose nodes keep a parent pointer. that pointer is what makes "explode" manageable: to add a pair's left value to the nearest number on its left, the code climbs until it comes from a right child, then takes the rightmost leaf of the sibling subtree (and the mirror image for the right side).

reduction repeats "explode the first pair nested four deep, otherwise split the first number over 9" until nothing changes. part 1 adds the whole list and takes the magnitude (3 × left + 2 × right). part 2 tries every ordered pair of numbers, cloning them first since reduction mutates the trees.

the trick

parent pointers turn "the nearest number to the left" into a short walk up and back down the tree.

python
def _prev(n):
    p = n
    while p.parent and p.parent.l == p:
        p = p.parent
    if not p.parent or p.parent.l == p:
        return None
    return rightmost(p.parent.l)