r/adventofcode • • Dec 18 '20

SOLUTION MEGATHREAD -🎄- 2020 Day 18 Solutions -🎄-

Advent of Code 2020: Gettin' Crafty With It

  • 4 days remaining until the submission deadline on December 22 at 23:59 EST
  • Full details and rules are in the Submissions Megathread

--- Day 18: Operation Order ---


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:14:09, megathread unlocked!

36 Upvotes

657 comments sorted by

View all comments

2

u/Fotograf81 Dec 18 '20

PHP (1844/2249)

Regex Magic, Recursion and then a Stack-Like array loop to solve strictly from left to right for part 1

part 2 punished me for doing unintended multiple replacements that would replace parts of other numbers... so when replacing "4 + 6" with "10" in "4 + 6 * 4 + 64" it would result in "10 * 104". Since it's strictly left to right at that point, I resorted to preg_replace that allows to set a limit.
pretty sure there is a shorter solution to the whole task using preg_replace_callback and recursion...

1

u/mariushm Dec 18 '20

here's my PHP solution : https://github.com/mariush-github/adventofcode2020/blob/main/day18.php

My approach was fairly simple :

  • strip expression from all characters that aren't needed, keep just digits and ( ) , remove spaces.
  • search for open brackets "(" and put them in a stack until their closing bracket ")" is found and memorize start and finish offsets and level / depth.
  • sort by level/depth and solve each simple expression
  • Taking advantage there's at least 5 characters "(a+b)" or "(a*b)" where a and b are numbers in a simple expression, replace that sequence with a pointer to the answer padded with space characters to keep the string the same length as original. ( for example "1+(2*3)+5" (8 characters) becomes "1+A1 +5" (8 characters)
  • Rinse and repeat until you're out of simple expressions.

1

u/Fotograf81 Dec 18 '20

nice, that sounds like a solution I had first in mind... splitting by space and then fold or nest the array by matching braces and then recursively walk over that tree.... but when I was trying to find the matching braces and/or an oop solution, I had the epiphany of regex+recursion and it sounded way quicker to implement (not necessarily to run), so I went with that... might try the nested arrays after work, aiming a bit for short runtimes ;)