2020 day 18
This commit is contained in:
parent
94715f152b
commit
7084b96b4b
5 changed files with 435 additions and 0 deletions
32
2020/18/part2.js
Normal file
32
2020/18/part2.js
Normal file
|
@ -0,0 +1,32 @@
|
|||
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))
|
||||
)
|
||||
}
|
||||
// if there's addition, do that
|
||||
while (expression.match(/\+/)){
|
||||
expression = expression.replace(/(\d+) \+ (\d+)/, (match, a, b) =>
|
||||
parseInt(a) + parseInt(b)
|
||||
)
|
||||
}
|
||||
// if there's multiplication, do that
|
||||
while (expression.match(/\*/)) {
|
||||
expression = expression.replace(/(\d+) \* (\d+)/, (match, a, 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