AdventOfCode2024/02/index.ts

62 lines
1.4 KiB
TypeScript

import fs from "node:fs";
const data = fs.readFileSync("./inputs/input", "utf8");
type collector = { ok: boolean; inc: boolean; dec: boolean };
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[][] => {
return Array.from({ length: report.length }, (_, i) => [
...report.slice(0, i),
...report.slice(i + 1),
]);
};
console.log(
"part one:",
data
.split("\n")
.slice(0, -1) // remove empty trailing newline
.map((v) => v.split(" ").map((c) => parseInt(c, 10)))
.reduce(
(total, current) =>
isOK(current.reduce(reducer, init)) ? total + 1 : total,
0
)
);
console.log(
"part two:",
data
.split("\n")
.slice(0, -1) // remove empty trailing newline
.map((v) => v.split(" ").map((c) => parseInt(c, 10)))
.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
)
);