clean up the code a little more

This commit is contained in:
David 2024-12-04 22:38:21 -05:00
parent 172adce0ba
commit 9e99375349
2 changed files with 47 additions and 40 deletions

View File

@ -14,31 +14,30 @@ console.log(
data
.split("\n")
.slice(0, -1)
.reduce((coll, curr, index, array) => {
// 2D string matching is a pain. Let's turn it into a 1D problem!
// create the columns
curr.split("").forEach((s, i) => {
coll[i] = coll[i] ? coll[i] + s : s;
});
// create the down-left-diagonals
curr.split("").forEach((s, i) => {
coll[i + array.length + index] = coll[i + array.length + index]
? coll[i + array.length + index] + s
: s;
});
// create the down-right-diagonals
curr.split("").forEach((s, i) => {
coll[array.length * 4 + index - i - 2] = coll[
array.length * 4 + index - i - 2
]
? coll[array.length * 4 + index - i - 2] + s
: s;
});
// include the original row
return [...coll, curr];
}, Array.from({ length: test ? 10 + (10 * 4 - 2) : 140 + 140 * 4 - 2 }) as string[])
.reduce(
(coll, curr, index, array) => {
// 2D string matching is a pain. Let's turn it into a 1D problem!
// create the columns
curr.split("").forEach((s, i) => {
coll[i] += s;
});
// create the down-left-diagonals
curr.split("").forEach((s, i) => {
coll[i + array.length + index] += s;
});
// create the down-right-diagonals
curr.split("").forEach((s, i) => {
coll[array.length * 4 + index - i - 2] += s;
});
// include the original row
return [...coll, curr];
},
// pre-populate the array so everything's aligned
Array.from({ length: test ? 10 * 5 - 2 : 140 * 5 - 2 }, () => "")
)
.reduce((total, curr) => {
// and now just do some regexes over the set of 1D strings
// can't do /XMAS|SMAX/ because overlaps like XMASAMX are allowed!
let matchesForward = curr.match(/XMAS/g);
let matchesBackward = curr.match(/SAMX/g);
if (matchesForward) {
@ -64,25 +63,28 @@ console.log(
return coll;
}
// look for A's
curr.split("").forEach((s, i, a) => {
if (i === 0 || i === a.length - 1) {
// same as above, edges are useless
return;
}
if (s === "A") {
return [
...coll,
...curr.split("").reduce((c, s, i, a) => {
if (i === 0 || i === a.length - 1) {
// same as above, edges are useless
return c;
}
// 1 2
// A
// 3 4
coll = [
...coll,
array[index - 1][i - 1] +
array[index - 1][i + 1] +
array[index + 1][i - 1] +
array[index + 1][i + 1],
];
}
});
return coll;
if (s === "A") {
return [
...c,
array[index - 1][i - 1] +
array[index - 1][i + 1] +
array[index + 1][i - 1] +
array[index + 1][i + 1],
];
}
return c;
}, [] as string[]),
];
}, [] as string[])
.reduce((coll, curr) => {
// we could have just done this check above,

View File

@ -1,7 +1,12 @@
import fs from "node:fs";
import { printTime, now } from "../util";
const data = fs.readFileSync("./inputs/input", "utf8");
const test = false;
const data = fs.readFileSync(
test ? "./inputs/testinput" : "./inputs/input",
"utf8"
);
let timer = now.instant();
console.log(