Add day 4
This commit is contained in:
parent
195db00b79
commit
bbab540d22
2 changed files with 133 additions and 0 deletions
53
javascript/day_04/part2.mjs
Normal file
53
javascript/day_04/part2.mjs
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
"use strict";
|
||||
|
||||
import { readFile } from "fs/promises";
|
||||
|
||||
if (process.argv.length <= 2) {
|
||||
console.error(`Needs more args >:(`).
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
const fileToRead = process.argv[2];
|
||||
const file = await readFile(fileToRead, `utf-8`);
|
||||
|
||||
/** @type {Array<Array<string>>} */
|
||||
const wordSearch = [];
|
||||
|
||||
for (const line of file.split(`\n`)) {
|
||||
wordSearch.push(line.split(``));
|
||||
};
|
||||
|
||||
|
||||
let total = 0;
|
||||
|
||||
// Iterating the puzzle space, which is reduced by one in both axis'
|
||||
// in order to reducing the number of iterations since we can't match
|
||||
// along the edges anyway
|
||||
for (let y = 1, l1 = wordSearch.length - 1; y < l1; y++) {
|
||||
for (let x = 1, l2 = wordSearch[y].length - 1; x < l2; x++) {
|
||||
|
||||
|
||||
// Short-circuit for performance
|
||||
const middle = wordSearch[y][x];
|
||||
if (`A` !== middle) {
|
||||
continue;
|
||||
};
|
||||
|
||||
try {
|
||||
const ne = wordSearch[y - 1][x + 1];
|
||||
const se = wordSearch[y + 1][x + 1];
|
||||
const sw = wordSearch[y + 1][x - 1];
|
||||
const nw = wordSearch[y - 1][x - 1];
|
||||
|
||||
let valid = ne === nw && se === sw;
|
||||
valid ||= ne === se && nw === sw;
|
||||
|
||||
valid &&= (ne === `M` && se === `S`) || (ne === `S` || se === `M`);
|
||||
|
||||
if (valid) total += 1;
|
||||
} catch (c){console.error(c)}
|
||||
|
||||
};
|
||||
};
|
||||
|
||||
console.log(`Found ${total} instances of X'd MAS`);
|
||||
Loading…
Add table
Add a link
Reference in a new issue