r/adventofcode • u/daggerdragon • Dec 18 '21
SOLUTION MEGATHREAD -🎄- 2021 Day 18 Solutions -🎄-
NEW AND NOTEWORTHY
- From /u/jeroenheijmans: Reminder: unofficial Advent of Code survey 2021 (closes Dec 22nd)
- FYI: 23:59 Amsterdam time zone is 17:59 EST
Advent of Code 2021: Adventure Time!
- 5 days left to submit your adventures!
- Full details and rules are in the submissions megathread: 🎄 AoC 2021 🎄 [Adventure Time!]
--- Day 18: Snailfish ---
Post your code solution in this megathread.
- Include what language(s) your solution uses!
- Format your code appropriately! How do I format code?
- Here's a quick link to /u/topaz2078's
pasteif you need it for longer code blocks. - The full posting rules are detailed in the wiki under How Do The Daily Megathreads Work?.
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
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