day 08
memory maneuver
approach
the input is one list of numbers, and parse walks it through a single shared iterator. each call reads a node's child count and metadata count, recursively parses its children, then reads its metadata, and returns the node as a (metadata, children) tuple.
part 1 sums the metadata over the whole tree. part 2 computes a node's value: the sum of its metadata if it has no children, otherwise the sum of the values of the children its metadata entries point to (1-based, skipping out-of-range entries). both are plain recursive functions, called by hand.
the trick
pass one iterator down the recursion, so each call consumes exactly its own node and the next call starts in the right place.
python
def parse(it):
# read the number of children and number of metadata
num_children, num_metadata = next(it), next(it)
# recursively parse children nodes
children = [parse(it) for _ in range(num_children)]
# read the metadata
metadata = [next(it) for _ in range(num_metadata)]
return (metadata, children)