DEV Community

loading...

Discussion on: Advent of Code 2020 Solution Megathread - Day 18: Operation Order

Collapse
kudostoy0u profile image
Kudos Beluga • Edited

Javascript solution part 1, I'll see what I can do about part 2.
I used iteration to solve this instead of parsing algorithm thingamajigs, and now I feel I should have gone that way :/

const fs = require("fs");
let data = fs.readFileSync("input.txt", "utf8").split("\n");
const balancedp = (idx, eq) => {
    let totall = 0;
    let endingindex;
    for (let i = idx, n = eq.length; i < n; i++) {
        let currentchar = eq[i];
        if (currentchar == "(") totall++
        else if (currentchar == ")") totall--
        if (totall == 0) {
            endingindex = i;
            break;
        }
    }
    return [eq.slice(idx + 1, endingindex), endingindex]
}
const tonumber = n => n.map(e => Number(e))
const processequation = eq => {
    if (eq[0] == "(") {
        return processequation("0 + " + eq)
    } else {
        let fidx = eq.match(/\d+/)
        let fnum = fidx[0]
        let op = eq.match(/(?<=\d+ )(\*|\+)/)[0];
        let lidx = eq.match(/(?<=\d+ (\*|\+) )(\(|\d+)/).index
        let lnum = eq.slice(lidx).split(" ")[0]
        if (lnum[0] == "(") lnum = "(";
        if (lnum == "(") {
            let sol = balancedp(lidx, eq);
            lidx = sol[1];
            lnum = processequation(sol[0]);
        }
        [lnum, fnum] = tonumber([lnum, fnum])
        if (op == "+") {
            eq = lnum + fnum + eq.slice(lidx + 1)
        } else {
            eq = fnum * lnum + eq.slice(lidx + 1)
        }
        let e = Number(eq)
        if (e) return Number(e)
        else return processequation(eq)
    }
}
let total = 0;
for (let i = 0, n = data.length; i < n; i++) {
    total += processequation(data[i]);
}
Enter fullscreen mode Exit fullscreen mode

Minified,

let e=require("fs").readFileSync("input.txt","utf8").split("\n");const t=e=>{if("("==e[0])return t("0 + "+e);{let l=e.match(/\d+/)[0],r=e.match(/(?<=\d+ )(\*|\+)/)[0],i=e.match(/(?<=\d+ (\*|\+) )(\(|\d+)/).index,n=e.slice(i).split(" ")[0];if("("==n[0]&&(n="("),"("==n){let l=((e,t)=>{let l,r=0;for(let i=e,n=t.length;i<n;i++){let e=t[i];if("("==e?r++:")"==e&&r--,0==r){l=i;break}}return[t.slice(e+1,l),l]})(i,e);i=l[1],n=t(l[0])}[n,l]=[n,l].map(e=>Number(e)),e="+"==r?n+l+e.slice(i+1):l*n+e.slice(i+1);let c=Number(e);return c?Number(c):t(e)}};let l=0;for(let r=0,i=e.length;r<i;r++)l+=t(e[r])
Enter fullscreen mode Exit fullscreen mode