day 09
explosives in cyberspace
approach
part 1 actually builds the decompressed string: it scans the input, and at each (AxB) marker it copies the next A characters B times and jumps past them, so markers inside a repeated block are left as plain text. the answer is the length of the result.
part 2 never builds the string. the input is parsed recursively into a tree, where a marker becomes a node holding its length and repeat count, its children are whatever is found inside the span it covers, and a plain character is a leaf worth 1. a depth-first walk then adds up the lengths, multiplying each node's total by its repeat count.
the trick
only the length is needed, so nested markers become a tree of multipliers instead of an expanded string.
python
def dfs(node):
if not node.children:
return node.times * node.length
s = 0
for child in node.children:
if type(child) is Node:
r = dfs(child)
s += node.times * r
else:
s += node.times * child
return s