aoc-2024/day4/part2.ts

50 lines
1.1 KiB
TypeScript
Raw Normal View History

2024-12-05 06:08:04 +00:00
const inputFile = await Bun.file("input").text();
const lines = inputFile.split("\n").filter((x) => x);
function between(x: number, min: number, max: number): boolean {
return x >= min && x < max;
}
function countMs(str: string) {
return (str.match(/M/g) || []).length;
}
function countSs(str: string) {
return (str.match(/S/g) || []).length;
}
let xmasCount = 0;
for (let lineIdx = 0; lineIdx < lines.length; lineIdx++) {
for (let charIdx of lines[lineIdx]
.matchAll(/A/g)
.toArray()
.map((m) => m.index)) {
let charPositions = [
[lineIdx - 1, charIdx - 1], // up left
[lineIdx - 1, charIdx + 1], // up right
[lineIdx + 1, charIdx - 1], // down left
[lineIdx + 1, charIdx + 1], // down right
].filter(
([li, ci]) =>
between(li, 0, lines.length) && between(ci, 0, lines[lineIdx].length),
);
if (charPositions.length === 4) {
let corners = "";
for (let [li, ci] of charPositions) {
corners += lines[li][ci];
}
if (countMs(corners) == 2 && countSs(corners) == 2) {
xmasCount += 1;
}
}
}
}
console.log(xmasCount);
export {};