-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.ts
executable file
·103 lines (82 loc) · 2.65 KB
/
main.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
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
#!/usr/bin/env deno run --allow-read
import { assertEquals } from "https://deno.land/[email protected]/testing/asserts.ts";
import {
Coord,
CoordSet,
indexWithCoord,
product,
sum,
} from "../../2020/utils.ts";
const parseInput = (string: string): number[][] =>
string.trim().split("\n").map((line) => {
return line.trim().split("").map((s) => parseInt(s, 10));
});
const text = await Deno.readTextFile("input.txt");
export const input = parseInput(text);
export const findNeighbors = (input: number[][], [x, y]: Coord) => {
const neighbors: Coord[] = [];
if (y > 0) neighbors.push([x, y - 1]);
if (x > 0) neighbors.push([x - 1, y]);
if (y < input.length - 1) neighbors.push([x, y + 1]);
if (x < input[y].length - 1) neighbors.push([x + 1, y]);
return neighbors;
};
export const findLowPoints = (input: number[][]): Coord[] => {
const lowPoints: Coord[] = [];
for (let y = 0; y < input.length; y++) {
for (let x = 0; x < input[y].length; x++) {
const point: Coord = [x, y];
const neighbors = findNeighbors(input, point);
const value = indexWithCoord(input, point);
const isLowPoint = neighbors.every((n) =>
value < indexWithCoord(input, n)
);
if (isLowPoint) {
lowPoints.push(point);
}
}
}
return lowPoints;
};
export const lowPointRiskLevel = (input: number[][], lowPoints: Coord[]) =>
sum(lowPoints.map((p) => indexWithCoord(input, p) + 1));
const part1 = (input: number[][]): number => {
const lowPoints = findLowPoints(input);
return lowPointRiskLevel(input, lowPoints);
};
const example = parseInput(`
2199943210
3987894921
9856789892
8767896789
9899965678
`);
assertEquals(part1(example), 15);
console.log("Result part 1: " + part1(input));
export const largestBasinRating = (basins: CoordSet[]) => {
const basinSizes = basins.map((b) => b.size).sort((a, b) => b - a);
const largestSizes = basinSizes.slice(0, 3);
return product(largestSizes);
};
const part2 = (input: number[][]): number => {
const lowPoints = findLowPoints(input);
const basins = lowPoints.map((lowPoint) => {
const basin = new CoordSet();
basin.add(lowPoint);
const addNeighbors = (point: Coord) => {
const neighbors = findNeighbors(input, point);
neighbors.forEach((neighbor) => {
const neighborValue = indexWithCoord(input, neighbor);
if (neighborValue < 9 && !basin.has(neighbor)) {
basin.add(neighbor);
addNeighbors(neighbor);
}
});
};
addNeighbors(lowPoint);
return basin;
});
return largestBasinRating(basins);
};
assertEquals(part2(example), 1134);
console.log("Result part 2: " + part2(input));