aoc-2023/day_21/solve.ts

49 lines
1.4 KiB
TypeScript
Raw Normal View History

2024-12-09 22:41:02 +09:00
const input = await Deno.readTextFile("input.txt");
const initMap = input.split("\n").map(x => x.trim())
.filter(x => x.length > 0)
.map(x => x.split(""));
function map2d<T, S>(map: T[][], fn: (ch: T, x: number, y: number) => S): S[][] {
return map.map((line, y) => line.map((ch, x) => fn(ch, x, y)));
}
function mapToString(map: string[][]) {
return map.map(x => x.join("")).join("\n");
}
let map = map2d(initMap, (ch, x, y) => {
return ch === "S" ? "O" : ch;
});
for (let step = 0; step < 64; step++) {
// copy map
const nextMap = map2d(map, (ch) => { return ch; });
// propagate O
map2d(map, (ch, x, y) => {
if (ch === "O") {
nextMap[y][x] = ".";
if (x > 0 && map[y][x - 1] === ".") {
nextMap[y][x - 1] = "O";
}
if (x < map[0].length - 1 && map[y][x + 1] === ".") {
nextMap[y][x + 1] = "O";
}
if (y > 0 && map[y - 1][x] === ".") {
nextMap[y - 1][x] = "O";
}
if (y < map.length - 1 && map[y + 1][x] === ".") {
nextMap[y + 1][x] = "O";
}
}
return nextMap[y][x];
});
map = nextMap;
}
console.log(mapToString(map));
function countO(map: string[][]): number {
return map.flat().filter(x => x === "O").length
}
console.log(countO(map));