-
Notifications
You must be signed in to change notification settings - Fork 0
/
day7.ts
75 lines (61 loc) · 1.71 KB
/
day7.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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import fs from "node:fs";
const operands = ['+', '*', "||"];
const evaluateExpression = (arr: string[]) => {
let output = parseInt(arr[0]);
for (let i = 1; i < arr.length; i++) {
if (!operands.includes(arr[i])) {
if (arr[i - 1] === '*') {
output *= parseInt(arr[i]);
} else if (arr[i - 1] === '+') {
output += parseInt(arr[i]);
} else {
output = parseInt(`${output}${arr[i]}`);
}
}
}
return output;
};
try {
const data = fs.readFileSync('day7.txt', 'utf8');
let output1 = 0;
data.split("\n").filter(Boolean).forEach((l) => {
const values = l.split(":");
const testValue = values[0]?.trim();
const operators = values[1].trim().split(" ");
const check = (currValue: string[] = [], currIdx = 0): boolean => {
if (currIdx === operators.length) {
const res = evaluateExpression(currValue);
if (res === parseInt(testValue)) {
return true;
}
return false;
}
let hasConfig = false;
if (currIdx === operators.length - 1) {
currValue.push(operators[currIdx]);
hasConfig ||= check(currValue, currIdx + 1);
if (hasConfig) {
return hasConfig;
}
currValue.pop();
} else {
for (let i = 0; i < operands.length; i++) {
currValue.push(...[operators[currIdx], operands[i]]);
hasConfig ||= check(currValue, currIdx + 1);
if (hasConfig) {
return hasConfig;
}
currValue.pop();
currValue.pop();
}
}
return hasConfig;
};
if (check()) {
output1 += parseInt(testValue);
}
});
console.log(output1);
} catch (err) {
console.error(err);
}