2023-08-06 20:19:33 +02:00

101 lines
2.8 KiB
TypeScript

import { readLines } from "https://deno.land/std@0.177.1/io/read_lines.ts";
async function Part1() {
const file = await Deno.open("./Day9/input.txt");
const lines = readLines(file);
let map: number[][] = [];
for await (const line of lines) {
map.push([]);
for (const n of line) {
map[map.length -1].push(+n);
}
}
let result = 0;
for (const i in map) {
for (const j in map[i]) {
if (+i > 0 && map[i][j] >= map[+i-1][j]) {
continue
} else if (+j > 0 && map[i][j] >= map[i][+j - 1]) {
continue
} else if (+i < map.length - 1 && map[i][j] >= map[+i + 1][j]) {
continue
} else if (+j < map[i].length - 1 && map[i][j] >= map[i][+j + 1]) {
continue
}
//console.log(i,j)
result += map[i][j] + 1;
}
}
return result
}
async function Part2() {
const file = await Deno.open("./Day9/input.txt");
const lines = readLines(file);
let map: number[][] = [];
const seen: boolean[][] = [];
for await (const line of lines) {
map.push([]);
seen.push([]);
for (const n of line) {
map[map.length -1].push(+n);
seen[seen.length -1].push(false);
}
}
const basinSizes = [];
for (const i in map) {
for (const j in map[i]) {
if (!seen[i][j] && map[i][j] != 9) {
let size = 1;
seen[i][j] = true;
const neigbours = getNeighbours(map,+i,+j);
while (neigbours.length != 0) {
const [a,b] = neigbours.pop()!;
if (map[a][b] == 9 || seen[a][b]) {
continue
}
size++
seen[a][b] = true;
for (const n of getNeighbours(map,a,b)) {
const [c,d] = n;
if (!seen[c][d]) {
neigbours.push([c,d]);
}
}
}
basinSizes.push(size);
}
}
}
basinSizes.sort((a,b) => a-b);
return basinSizes[basinSizes.length -1] * basinSizes[basinSizes.length -2] * basinSizes[basinSizes.length -3];
}
console.log("Part1: " + await Part1());
console.log("Part2: " + await Part2())
function getNeighbours(map: number[][],i:number,j:number) {
const neighbours: [number,number][] = [];
if (+i > 0) {
neighbours.push([i-1,j])
}
if (+j > 0) {
neighbours.push([i,j-1])
}
if (+i < map.length - 1) {
neighbours.push([i+1,j])
}
if (+j < map[i].length - 1) {
neighbours.push([i,j+1])
}
return neighbours
}