-
Notifications
You must be signed in to change notification settings - Fork 5
/
day18.js
43 lines (35 loc) · 1015 Bytes
/
day18.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
const fs = require('fs');
const lines = fs.readFileSync('day18.txt', {encoding: 'utf-8'}).split('\n').filter(x => x);
function solve(string) {
let tokens = string.split(' ');
while(tokens.length > 1) {
tokens = [eval(tokens.slice(0, 3).join(''))].concat(tokens.slice(3))
}
return tokens[0];
}
function solve2(string) {
while(/\+/.test(string)) {
string = string.replace(/(\d+) \+ (\d+)/g, (match, firstNumber, secondNumber) => {
return parseInt(firstNumber) + parseInt(secondNumber);
})
}
return eval(string);
}
function solveWithParenthesis(string, solve) {
while(/\(/.test(string)) {
string = string.replace(/\(([^()]+)\)/g, (match, group) => {
return solve(group);
})
}
return solve(string);
}
let sum = 0;
lines.forEach(line => {
sum += solveWithParenthesis(line, solve);
});
console.log(sum);
sum = 0;
lines.forEach(line => {
sum += solveWithParenthesis(line, solve2);
});
console.log(sum);