2020 day 18
This commit is contained in:
parent
94715f152b
commit
7084b96b4b
5 changed files with 435 additions and 0 deletions
26
2020/18/part1.js
Normal file
26
2020/18/part1.js
Normal file
|
@ -0,0 +1,26 @@
|
|||
const fs = require('fs');
|
||||
const expressions = fs.readFileSync('./input.txt', 'utf-8').split('\n');
|
||||
|
||||
function calc (expression) {
|
||||
// if it's just a number, do nothing
|
||||
if (!isNaN(Number(expression))) { Number(expression) }
|
||||
// if there's brackets, do that first
|
||||
while (expression.match(/\(/)){
|
||||
expression = expression.replace(/\([^()]+\)/, match =>
|
||||
calc (match.slice(1, match.length-1))
|
||||
)
|
||||
}
|
||||
// do all the calculations until it's just a number
|
||||
while (isNaN(Number(expression))) {
|
||||
expression = expression.replace(/(\d+) ([+*]) (\d+)/, (match, a, op, b) =>
|
||||
op == '+' ? parseInt(a) + parseInt(b) : parseInt(a) * parseInt(b)
|
||||
)
|
||||
}
|
||||
return Number(expression)
|
||||
}
|
||||
|
||||
let runningTotal = 0
|
||||
for (expression of expressions) {
|
||||
runningTotal += calc (expression)
|
||||
}
|
||||
console.log(runningTotal)
|
Loading…
Add table
Add a link
Reference in a new issue