This commit is contained in:
Zynh Ludwig 2024-12-04 22:08:04 -08:00
parent 221a81583a
commit 63261538ec
3 changed files with 54 additions and 4 deletions

3
.gitignore vendored Normal file
View file

@ -0,0 +1,3 @@
package.json
package-lock.json
node_modules

View file

@ -28,8 +28,6 @@ local lines = lines_from(file)
---@diagnostic disable-next-line: redefined-local ---@diagnostic disable-next-line: redefined-local
local function count_xmas_at_index(lines, line_idx, char_idx) local function count_xmas_at_index(lines, line_idx, char_idx)
local line = lines[line_idx]
local up_idx = line_idx - 1 local up_idx = line_idx - 1
local down_idx = line_idx + 1 local down_idx = line_idx + 1
local right_idx = char_idx + 1 local right_idx = char_idx + 1
@ -39,7 +37,7 @@ local function count_xmas_at_index(lines, line_idx, char_idx)
char_count["M"] = 0 char_count["M"] = 0
char_count["S"] = 0 char_count["S"] = 0
if up_idx >= 1 then if up_idx >= 1 then
if right_idx <= #line then if right_idx <= #lines[up_idx] then
local key = lines[up_idx]:sub(right_idx, right_idx) local key = lines[up_idx]:sub(right_idx, right_idx)
if char_count[key] ~= nil then if char_count[key] ~= nil then
char_count[key] = char_count[key] + 1 char_count[key] = char_count[key] + 1
@ -55,7 +53,7 @@ local function count_xmas_at_index(lines, line_idx, char_idx)
end end
if down_idx <= #lines then if down_idx <= #lines then
if right_idx <= #line then if right_idx <= #lines[down_idx] then
local key = lines[down_idx]:sub(right_idx, right_idx) local key = lines[down_idx]:sub(right_idx, right_idx)
if char_count[key] ~= nil then if char_count[key] ~= nil then
char_count[key] = char_count[key] + 1 char_count[key] = char_count[key] + 1

49
day4/part2.ts Normal file
View file

@ -0,0 +1,49 @@
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 {};