r/adventofcode • • Dec 18 '21

SOLUTION MEGATHREAD -🎄- 2021 Day 18 Solutions -🎄-

NEW AND NOTEWORTHY


Advent of Code 2021: Adventure Time!


--- Day 18: Snailfish ---


Post your code solution in this megathread.

Reminder: Top-level posts in Solution Megathreads are for code solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.

EDIT: Global leaderboard gold cap reached at 00:43:50, megathread unlocked!

45 Upvotes

595 comments sorted by

View all comments

1

u/gerolfscherr Dec 18 '21

Java

i think this is the first problem where the source code is bigger than the problem description, even if it is so detailed. After thinking about some regex / match / I decided to develop a clean solution and wrote a simple parser (based on jack crenshaw's ideas from the late eighties, see https://compilers.iecc.com/crenshaw/

which returns a classic binary tree structure.

I was struggling a little bit on how to express the notion of the 'left/right' items in the explode function. By reading the description and the flattened representation its obvoius what 'left'/'right' means, but how to navigate to that node in the tree?

Well it turns out, the left number is the last number visited in an in-order-traversal, just before you encounter the 'exploding' node. the right number is the next one after the 'exploding' node. (or: the last one, if you are doing in-order-traversal with left/right subtrees swapped). Basically we are doing the same as in the toString() function.

After all this work, a lot of testcases and a lot of (maybe superflous - but you never know) consistency checks in the Nodes it all boils down to this function:

Node add(Node l, Node r) {
if (l == null) return r;
Node n = new Node(l, r);
while (n.doExplode() || n.doSplit());
return n;
}

With part1 running, part two was only a matter of a few minutes.

Full source:

https://github.com/gerolfscherr/aoc2021/blob/main/src/main/java/AOC18.java

1

u/daggerdragon Dec 18 '21

FYI: Your code is hard to read on old.reddit when the code "block" is inlined like this and all the whitespace gets stripped out. Please edit it to use a proper code block as per our posting guidelines in the wiki: How do I format code?