-
Notifications
You must be signed in to change notification settings - Fork 0
/
part1.ts
28 lines (23 loc) · 947 Bytes
/
part1.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
import * as fs from 'fs';
import { getNeighborPositions } from '../../utils';
const input = fs.readFileSync('input', 'utf8').split('\n').map((line => line.split('').map(Number)));
const getIncrementNeighborPositions = (x: number, y: number) =>
getNeighborPositions(input, x, y)
.filter((neighborPosition) => input[neighborPosition.y][neighborPosition.x] === input[y][x] + 1);
const getTrailEnds = (x: number, y: number) => {
if (input[y][x] === 9) return new Set([`${x},${y}`]);
const incrementNeighborPositions = getIncrementNeighborPositions(x, y);
if (incrementNeighborPositions.length > 0) {
return incrementNeighborPositions.reduce((acc, pos) => new Set([...acc, ...getTrailEnds(pos.x, pos.y)]), new Set());
}
return new Set();
}
let result = 0;
for (let x = 0; x < input.length; x++) {
for (let y = 0; y < input[x].length; y++) {
if (input[y][x] === 0) {
result += getTrailEnds(x, y).size;
}
}
}
console.log(result);