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 :/
thingamajigs
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]); }
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])
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
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 :/Minified,