diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e8625c1 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +package.json +package-lock.json +node_modules diff --git a/day4/part2.lua b/day4/part2.lua index 2e88e07..87d2ae3 100644 --- a/day4/part2.lua +++ b/day4/part2.lua @@ -28,8 +28,6 @@ local lines = lines_from(file) ---@diagnostic disable-next-line: redefined-local local function count_xmas_at_index(lines, line_idx, char_idx) - local line = lines[line_idx] - local up_idx = line_idx - 1 local down_idx = line_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["S"] = 0 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) if char_count[key] ~= nil then char_count[key] = char_count[key] + 1 @@ -55,7 +53,7 @@ local function count_xmas_at_index(lines, line_idx, char_idx) end 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) if char_count[key] ~= nil then char_count[key] = char_count[key] + 1 diff --git a/day4/part2.ts b/day4/part2.ts new file mode 100644 index 0000000..bf2ec70 --- /dev/null +++ b/day4/part2.ts @@ -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 {};