-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3.mjs
More file actions
106 lines (88 loc) · 2.69 KB
/
Copy path3.mjs
File metadata and controls
106 lines (88 loc) · 2.69 KB
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import { getAdjacentPositions, readInput } from "./utils.mjs";
const input = readInput(import.meta);
const parseInput = (input) => input.split("\n");
const isSymbol = (char) => !/\d|\./.test(char);
const isNumber = (char) => /\d/.test(char);
const getNumberPositions = (lines, i, j, dir = "rl") => {
if (
i < 0 ||
j < 0 ||
i > lines[0].length ||
j > lines.length ||
!isNumber(lines[i][j])
) {
return [];
}
if (dir === "rl") {
return [
...getNumberPositions(lines, i, j - 1, "l"),
[i, j],
...getNumberPositions(lines, i, j + 1, "r"),
];
}
if (dir === "r") {
return [[i, j], ...getNumberPositions(lines, i, j + 1, "r")];
}
return [...getNumberPositions(lines, i, j - 1, "l"), [i, j]];
};
const hashNumberPositions = (arrayIj) =>
arrayIj.map((ij) => ij.join(",")).join(";");
const getNumber = (lines, hashedNumberPositions) =>
+hashedNumberPositions
.split(";")
.reduce(
(numStr, ij) => numStr + lines[ij.split(",")[0]][ij.split(",")[1]],
"",
);
const solve1 = (input) => {
const lines = parseInput(input);
const symbolAdjacentPositions = [];
for (let i = 0; i < lines.length; i++) {
for (let j = 0; j < lines[i].length; j++) {
if (isSymbol(lines[i][j])) {
symbolAdjacentPositions.push(...getAdjacentPositions(i, j));
}
}
}
const uniqueNumberPositions = new Set();
for (const [i, j] of symbolAdjacentPositions) {
const numberPositions = getNumberPositions(lines, i, j);
if (numberPositions.length) {
uniqueNumberPositions.add(hashNumberPositions(numberPositions));
}
}
return [...uniqueNumberPositions].reduce(
(acc, hashedNumberPositions) =>
acc + getNumber(lines, hashedNumberPositions),
0,
);
};
const couldBeGear = (char) => char === "*";
const solve2 = (input) => {
const lines = parseInput(input);
let result = 0;
for (let i = 0; i < lines.length; i++) {
for (let j = 0; j < lines[i].length; j++) {
if (couldBeGear(lines[i][j])) {
const adjacentPositions = getAdjacentPositions(i, j);
const uniqueNumberPositions = new Set();
for (const [i, j] of adjacentPositions) {
const numberPositions = getNumberPositions(lines, i, j);
if (numberPositions.length) {
uniqueNumberPositions.add(hashNumberPositions(numberPositions));
}
}
if (uniqueNumberPositions.size >= 2) {
result += [...uniqueNumberPositions].reduce(
(acc, hashedNumberPositions) =>
acc * getNumber(lines, hashedNumberPositions),
1,
);
}
}
}
}
return result;
};
console.log(solve1(input));
console.log(solve2(input));