refactor day 2 considerably

This commit is contained in:
David 2024-12-02 23:12:06 -05:00
parent 0f20a09f6f
commit 0199cc2d68

View File

@ -2,33 +2,31 @@ import fs from "node:fs";
const data = fs.readFileSync("./inputs/input", "utf8");
type runner = { ok: boolean; prev: number; inc: boolean; dec: boolean };
type collector = { ok: boolean; inc: boolean; dec: boolean };
const testFunc = (running: runner, current: number, i: number) => {
if (i === 0) {
return { ok: true, prev: current, inc: false, dec: false };
}
if (!running.ok) {
// quick exit
return running;
}
const diff = Math.abs(running.prev - current);
return {
ok: diff > 0 && diff < 4,
prev: current,
inc: running.inc || running.prev - current > 0,
dec: running.dec || running.prev - current < 0,
};
const init = {
ok: true,
inc: false,
dec: false,
};
const reducer = (col: collector, curr: number, i: number, a: number[]) =>
i === 0 || !col.ok
? col
: {
ok:
a[i - 1] - curr > -4 && a[i - 1] - curr !== 0 && a[i - 1] - curr < 4,
inc: col.inc || a[i - 1] - curr > 0,
dec: col.dec || a[i - 1] - curr < 0,
};
const isOK = (r: collector): boolean => r.ok && !(r.inc && r.dec);
const permute = (report: number[]): number[][] => {
const result: Array<Array<number>> = Array.from(
{ length: report.length },
() => []
);
return result.map((_, i) => {
return [...report.slice(0, i), ...report.slice(i + 1)];
});
return Array.from({ length: report.length }, (_, i) => [
...report.slice(0, i),
...report.slice(i + 1),
]);
};
console.log(
@ -37,10 +35,11 @@ console.log(
.split("\n")
.slice(0, -1) // remove empty trailing newline
.map((v) => v.split(" ").map((c) => parseInt(c, 10)))
.reduce((total, current) => {
const tmp = current.reduce(testFunc, {} as runner);
return (tmp.inc && tmp.dec) || !tmp.ok ? total : total + 1;
}, 0)
.reduce(
(total, current) =>
isOK(current.reduce(reducer, init)) ? total + 1 : total,
0
)
);
console.log(
@ -49,18 +48,14 @@ console.log(
.split("\n")
.slice(0, -1) // remove empty trailing newline
.map((v) => v.split(" ").map((c) => parseInt(c, 10)))
.reduce((total, current) => {
const tmp = current.reduce(testFunc, {} as runner);
// ok, that was fine.
if (tmp.ok && !(tmp.inc && tmp.dec)) {
return total + 1;
}
// otherwise, brute force!
const tmp2 = permute(current)
.map((v) => v.reduce(testFunc, {} as runner))
.reduce((coll, curr) => {
return coll || (curr.ok && !(curr.inc && curr.dec));
}, false);
return tmp2 ? total + 1 : total;
}, 0)
.reduce(
(total, current) =>
isOK(current.reduce(reducer, init)) ||
permute(current)
.map((v) => v.reduce(reducer, init))
.reduce((coll, curr) => coll || isOK(curr), false)
? total + 1
: total,
0
)
);