ugh day 2 part 2 sucked
This commit is contained in:
parent
be0f9029a4
commit
0f20a09f6f
66
02/index.ts
Normal file
66
02/index.ts
Normal file
@ -0,0 +1,66 @@
|
||||
import fs from "node:fs";
|
||||
|
||||
const data = fs.readFileSync("./inputs/input", "utf8");
|
||||
|
||||
type runner = { ok: boolean; prev: number; 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 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)];
|
||||
});
|
||||
};
|
||||
|
||||
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) => {
|
||||
const tmp = current.reduce(testFunc, {} as runner);
|
||||
return (tmp.inc && tmp.dec) || !tmp.ok ? total : total + 1;
|
||||
}, 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) => {
|
||||
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)
|
||||
);
|
Loading…
Reference in New Issue
Block a user