+62
day06/part2.ts
+62
day06/part2.ts
···
1
+
import { readFileSync } from "fs";
2
+
3
+
let input = readFileSync("./input.txt", "utf8").split(/\n/);
4
+
5
+
const operatorIndices = [...input[input.length - 1].matchAll(/\*|\+/g)].map(
6
+
(match) => match.index
7
+
);
8
+
const tokenizedInput = input.map((line) => {
9
+
const output = [];
10
+
11
+
for (let i = 0; i < operatorIndices.length; i++) {
12
+
output.push(
13
+
line.slice(
14
+
operatorIndices[i],
15
+
i + 1 < operatorIndices.length
16
+
? operatorIndices[i + 1]
17
+
: line.length
18
+
)
19
+
);
20
+
}
21
+
22
+
return output;
23
+
});
24
+
25
+
const mathProblems = new Array(tokenizedInput[0].length)
26
+
.fill(null)
27
+
.map((n) => [] as any);
28
+
29
+
for (let i = 0; i < tokenizedInput.length; i++) {
30
+
for (let j = 0; j < tokenizedInput[i].length; j++) {
31
+
mathProblems[j].push(tokenizedInput[i][j]);
32
+
}
33
+
}
34
+
35
+
let answersSum = 0;
36
+
37
+
for (let mathProblem of mathProblems) {
38
+
const mp = new Array(mathProblem[0].length)
39
+
.fill(null)
40
+
.map(() => [] as string[]);
41
+
42
+
for (let i = 0; i < mathProblem.length - 1; i++) {
43
+
for (let j = 0; j < mathProblem[i].length; j++) {
44
+
mp[j].push(mathProblem[i][j] ? mathProblem[i][j] : "");
45
+
}
46
+
}
47
+
48
+
mathProblem = {
49
+
operands: mp
50
+
.map((tokens) => tokens.join("").trim())
51
+
.filter(Boolean)
52
+
.map(Number),
53
+
operator: mathProblem[mathProblem.length - 1].trim()
54
+
};
55
+
56
+
answersSum +=
57
+
mathProblem.operator === "+"
58
+
? mathProblem.operands.reduce((a: any, c: any) => a + c, 0)
59
+
: mathProblem.operands.reduce((a: number, c: number) => a * c, 1);
60
+
}
61
+
62
+
console.log(answersSum);