AoC 2021 D18: Snailfish
| Problem statement | Source code | Tags: Data structures
← Previous Back to AoC Index Next →
Part 1
The first barrier was how to parse the input. Lucky for me, this is valid JSON, so I could just use JSON.parse. I wonder what happens if I use C++.
The next challenge was how to represent snailfish numbers. I went with the most straightforward approach: a binary tree where each node is either a pair (with left and right children) or a regular number (a leaf node). Since we later need upward traversal during explosion, I also stored a parent pointer.
Building the tree from the parsed JSON is just a matter of "inflating" each level of arrays into objects.
My code for explode is just a huge spaghetti. The signature is function explode(a: SnailNum, depth: number): boolean, which returns whether an explosion happened.
-
If
ais a number, it can't explode, so return false. -
If
depthis less than 4, or it's not a pair of numbers, we can't explode here, so recursively callexplodeon the left and right children.explode(a.left, depth + 1) || explode(a.right, depth + 1)ensures we only explode one pair. -
Otherwise, we've found a pair to explode. We need to find the nearest regular number to the left and right. To do this, we first move up until we find a parent where we are the right child (for left) or left child (for right). Then we move down the opposite subtree along the opposite children (left for left, right for right) until we reach a number. Finally, we add the exploding pair's values to these numbers (if they exist) and replace the exploding pair with a 0. For example, here's the left part:
As for split, the idea is similar.
- If
ais not a number, recursively callspliton the left and right children. - If
ais a number and less than 10, return false. - Otherwise, split
ainto a pair of two numbers and return true.
Once we have explode and split, add is straightforward.
In part 1, we just need to add them up:
Part 2
In part 2, we just pairwise add all snailfish numbers and compute the maximum magnitude.