Skip to content
advent of code 2021

day 16

packet decoder

approach

the hex input is expanded into one long bit string, and a recursive decode walks it from an index. each packet reads a 3-bit version and a 3-bit type. type 4 is a literal, read 5 bits at a time until a group starts with 0. any other type is an operator whose children are given either by total bit length (15-bit field) or by count (11-bit field), and decode recurses into them, returning where each packet ends.

part 1 sums the versions over the whole tree. part 2 evaluates it: sum, product, min, max, and the three comparisons that return 1 or 0.

the trick

have the parser return where each packet ends, so a parent knows where its next child starts.

python
def _eval(node):
    if node.tid == 4:
        return node.v
    elif node.tid == 0:
        return sum(_eval(nn) for nn in node.children)
    elif node.tid == 1:
        return prod(_eval(nn) for nn in node.children)
    ...