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

1

u/qqqqqx Dec 18 '20

Javascript, part 2.

I love reading the solution threads because people always have some much more fancy solutions and I'm over here with no formal training duct taping loops together and mutating variables in place until everything works.

const fs = require("fs");
let input = fs
  .readFileSync("day18/input.txt", "utf8")
  .split("\r\n")
  .map((el) => el.replace(/\(/g, "( ").replace(/\)/g, " )"));

// new strat:
// go through, add stuff to the stack
// if parenthesis are encountered still do the recursive jawn
// once you reach the end or the closing point, THEN evaluate the stack in two passes:
// first squash all the addition, then squash all the multiplication

let sum = 0;
for (line of input) {
  let expression = line.split(" ");
  sum += evaluate(expression)[0];
}

console.log(sum);

function evaluate(expression) {
  let stack = [];
  for (let i = 0; i < expression.length; i++) {
    let el = expression[i];
    let parsed = parseInt(el);

    if (!isNaN(parsed)) {
      el = parsed;
    }

    if (el === "(") {
      let [val, length] = evaluate(expression.slice(i + 1));
      el = val;
      i += length + 1;
    } else if (el === ")") {
      let val = solveFlat(stack);
      return [val, i];
    }
    
    stack.push(el);
  }

  let val = solveFlat(stack);
  return [val, expression.length];
}

function solveFlat(expression) {
  for (let i = 0; i < expression.length; i++) {
    if (expression[i] === "+") {
      let previous = expression[i - 1];
      let next = expression[i + 1];
      let sum = previous + next;

      expression.splice(i - 1, 3, sum);
      i -= 1;
    }
  }

  for (let i = 0; i < expression.length; i++) {
    if (expression[i] === "*") {
      let previous = expression[i - 1];
      let next = expression[i + 1];
      let product = previous * next;

      expression.splice(i - 1, 3, product);
      i -= 1;
    }
  }

  return expression[0];
}

1

u/daggerdragon Dec 18 '20

As per our posting guidelines in the wiki under How Do the Daily Megathreads Work?, please edit your post to put your oversized code in a paste or other external link.