-
Notifications
You must be signed in to change notification settings - Fork 0
/
d10.ts
53 lines (45 loc) · 1.21 KB
/
d10.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
import * as _ from "jsr:@es-toolkit/es-toolkit";
type Point = [number, number];
function parse(input: string) {
return input.split("\n").map((line) => line.split("").map(Number));
}
function score(visited: Point[][]) {
return _.sumBy(
visited,
(head: Point[]) => _.uniqBy(head, ([x, y]) => `${x},${y}`).length
);
}
function rating(visited: Point[][]) {
return _.sumBy(visited, (head: Point[]) => head.length);
}
function hike(map: number[][]) {
const paths: Point[][] = [];
function explore([i, j]: Point, h = 0, visited: Point[] = []) {
if (map[i][j] === 9) {
visited.push([i, j]);
return visited;
}
const neighbors = [
[i - 1, j],
[i + 1, j],
[i, j - 1],
[i, j + 1]
];
for (const [x, y] of neighbors) {
if (map[x]?.[y] === h + 1) {
explore([x, y], h + 1, visited);
}
}
return visited;
}
for (let i = 0; i < map.length; i++) {
for (let j = 0; j < map[i].length; j++) {
if (map[i][j] === 0) {
paths.push(explore([i, j]));
}
}
}
return paths;
}
export const p1 = (input: string): number => score(hike(parse(input)));
export const p2 = (input: string): number => rating(hike(parse(input)));