-
Notifications
You must be signed in to change notification settings - Fork 0
/
part2.ts
62 lines (57 loc) · 1.57 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
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
import * as fs from 'fs';
const input = fs.readFileSync('example', 'utf8').split('\n');
const getNumber = (indices: [number, number]) => {
const i = indices[0];
const j = indices[1];
let number = '' + input[i][j];
let jMinor = j;
while (jMinor > 0 && /\d/.test(input[i][--jMinor])) {
number = input[i][jMinor] + number;
}
let jPlus = j;
while (jPlus < input[0].length - 1 && /\d/.test(input[i][++jPlus])) {
number = number + input[i][jPlus];
}
return +number;
};
let result = 0;
for (let i = 0; i < input.length; i++) {
const matches = Array.from(input[i].matchAll(/\*/g));
for (const match of matches) {
const j = match.index;
const surrounding = [
(input[i - 1] ?? '')[j - 1] ?? '.',
(input[i - 1] ?? '')[j] ?? '.',
(input[i - 1] ?? '')[j + 1] ?? '.',
(input[i] ?? '')[j - 1] ?? '.',
(input[i] ?? '')[j] ?? '.',
(input[i] ?? '')[j + 1] ?? '.',
(input[i + 1] ?? '')[j - 1] ?? '.',
(input[i + 1] ?? '')[j] ?? '.',
(input[i + 1] ?? '')[j + 1] ?? '.',
];
const indices = [
[i - 1, j - 1],
[i - 1, j],
[i - 1, j + 1],
[i, j - 1],
[i, j],
[i, j + 1],
[i + 1, j - 1],
[i + 1, j],
[i + 1, j + 1],
];
const localNumberIndices = [];
for (let k = 0; k < surrounding.length; k++) {
if (/\d/.test(surrounding[k]) && (!/\d/.test(surrounding[k - 1] ?? '') || k % 3 == 0)) {
localNumberIndices.push(indices[k]);
}
}
if (localNumberIndices.length === 2) {
let number1 = getNumber(localNumberIndices[0]);
let number2 = getNumber(localNumberIndices[1]);
result += number1 * number2;
}
}
}
console.log(result);