63 lines
1.4 KiB
TypeScript
63 lines
1.4 KiB
TypeScript
const fs = require('fs');
|
|
|
|
const input = fs.readFileSync(__dirname + '/input.txt', 'utf8');
|
|
|
|
interface Coord { x: number, y: number };
|
|
|
|
const topo: Array<string> = input.split("\n").slice(0, -1);
|
|
|
|
const height = topo.length;
|
|
const width = topo[0].length;
|
|
|
|
|
|
let sum = 0;
|
|
|
|
function getScore({ x, y }: Coord, height = 0, trail: Array<Coord> = [], peaks: Array<string> = []): number {
|
|
let score = 0;
|
|
|
|
const nextHeight = height + 1;
|
|
[
|
|
{ x, y: y - 1 },
|
|
{ x, y: y + 1 },
|
|
{ x: x - 1, y },
|
|
{ x: x + 1, y },
|
|
].forEach((coord) => {
|
|
if (!topo[coord.y] || !topo[coord.y][coord.x]) {
|
|
return;
|
|
}
|
|
if (parseInt(topo[coord.y][coord.x]) === nextHeight) {
|
|
if (nextHeight === 9) {
|
|
const coordString = `${coord.x},${coord.y}`;
|
|
if (!peaks.includes(coordString)) {
|
|
score += 1;
|
|
// peaks.push(coordString); // Only for Part 1
|
|
}
|
|
} else {
|
|
score += getScore(coord, nextHeight, [...trail, { x, y }], peaks);
|
|
}
|
|
}
|
|
});
|
|
|
|
return score;
|
|
}
|
|
|
|
let y = 0;
|
|
let x = 0;
|
|
for (let i = 0; i <= input.length; i++) {
|
|
const char = input[i];
|
|
if (char === "\n") {
|
|
y++;
|
|
x = 0;
|
|
continue;
|
|
}
|
|
|
|
if (char === '0') {
|
|
const score = getScore({ x, y });
|
|
sum += score;
|
|
}
|
|
|
|
x++;
|
|
}
|
|
|
|
console.log(sum);
|