-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpart2.ts
35 lines (31 loc) · 1.16 KB
/
part2.ts
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
import * as fs from 'fs';
const input = fs
.readFileSync('input', 'utf8')
.split('\n')
.map((line) => line.split(': '));
const testValues = input.map((item) => Number(item[0]));
const equationValues = input.map((item) => item[1].split(' ').map(Number));
const checkEquation = (testValue: number, current: number, equationValues: number[]): boolean => {
if (current > testValue) return false;
const plusResult = current + equationValues[0];
const multipleResult = current * equationValues[0];
const concatenateResult = Number(`${current}${equationValues[0]}`);
if (equationValues.length === 1) {
return (
plusResult === testValue || multipleResult === testValue || concatenateResult === testValue
);
}
const newEquationValues = equationValues.slice(1);
return (
checkEquation(testValue, plusResult, newEquationValues) ||
checkEquation(testValue, multipleResult, newEquationValues) ||
checkEquation(testValue, concatenateResult, newEquationValues)
);
};
let result = 0;
for (let i = 0; i < testValues.length; i++) {
if (checkEquation(testValues[i], equationValues[i][0], equationValues[i].slice(1))) {
result += testValues[i];
}
}
console.log(result);