AoC 2021 D16: Packet Decoder
| Problem statement | Source code | Tags: Parsing
← Previous Back to AoC Index Next →
Part 1
I represent the packet tree as follows:
I parse the input into a binary string, then use a recursive descent parser to build the tree. The parser takes the input string and a starting index, and returns the parsed packet and the new index.
First we read the version and type ID:
If the type ID is 4, we read the literal value by repeatedly reading 5-bit groups until we find one that starts with a 0:
Otherwise, we first read the length type ID:
If the length type ID is 0, we read the next 15 bits for the bit length, and then continuously parse sub-packets until we've read that many bits:
Otherwise, if the length type ID is 1, we read the next 11 bits for the number of sub-packets, and then parse that many sub-packets:
In part 1, we visit this tree to sum all version numbers:
Part 2
In part 2, we again visit the tree, this time evaluating the packets based on their type IDs:
Where ops is defined as: