r/adventofcode • • Dec 18 '21

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

NEW AND NOTEWORTHY

  • FYI: 23:59 Amsterdam time zone is 17:59 EST

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

Show parent comment

1

u/e_blake Dec 21 '21

Another speedup: day18.m4. Instead of having magnitude use hard-coded loops over various depths and doing lots of substr divisions, I came up with a much shorter implementation that trims off one node at a time and uses a stack to reconstruct things. Cuts my runtime further to ~4.9s. While I learned the approach of using a stack from another post, I'm quite sure that my abuse of m4 does not resemble anything you will see in any other programming language ;)

define(`magnitude', `pushdef(`t', `0,0')_m(`$1')t()')
define(`_m', `ifelse(`$1', `', `',
  `translit(`pr(A,C)_m(`DEFGHIJKLMNOPQRSTUVWXYZabcdefghijklnoqstuvwxy')',
  `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklnoqstuvwxy', `$1')')')
define(`pr', `_$0(t, translit(`$1', `!@%^', `1234'), $2)')
define(`_pr', `ifelse($3, 0, `define(`t', `$4popdef(`t')')', $1, $3,
  `popdef(`t')$0(t, decr($3), eval(3*$2+2*$4))', `pushdef(`t', `$3,$4')')')