saw part 2 coming so it was indeed straightforward

This commit is contained in:
David 2024-12-06 13:51:12 -07:00
parent e7e1b615ff
commit 13667f414b

91
05/index.ts Normal file
View File

@ -0,0 +1,91 @@
import fs from "node:fs";
import { printTime, now } from "../util";
const test = false;
const data = fs.readFileSync(
test ? "./inputs/testinput" : "./inputs/input",
"utf8"
);
let timer = now.instant();
console.log(
"part one:",
(() => {
const { ordering, manuals } = data
.split("\n")
.slice(0, -1)
.reduce(
(coll, curr) => {
if (curr === "") {
return coll;
}
if (curr[2] === "|") {
return { ...coll, ordering: [...coll.ordering, curr.split("|")] };
}
if (curr[2] === ",") {
return { ...coll, manuals: [...coll.manuals, curr.split(",")] };
}
return coll;
},
{ ordering: [], manuals: [] } as {
ordering: Array<Array<string>>;
manuals: Array<Array<string>>;
}
);
return manuals.reduce((coll, curr) => {
const sorted = [...curr].sort((a, b) => {
return ordering.filter((v) => v[0] === a && v[1] === b).length === 0
? 1
: -1;
});
if (sorted.join(",") === curr.join(",")) {
return coll + parseInt(curr[Math.floor(curr.length / 2)], 10);
}
return coll;
}, 0);
})(),
printTime(now.instant().since(timer))
);
timer = now.instant();
console.log(
"part two:",
(() => {
const { ordering, manuals } = data
.split("\n")
.slice(0, -1)
.reduce(
(coll, curr) => {
if (curr === "") {
return coll;
}
if (curr[2] === "|") {
return { ...coll, ordering: [...coll.ordering, curr.split("|")] };
}
if (curr[2] === ",") {
return { ...coll, manuals: [...coll.manuals, curr.split(",")] };
}
return coll;
},
{ ordering: [], manuals: [] } as {
ordering: Array<Array<string>>;
manuals: Array<Array<string>>;
}
);
return manuals.reduce((coll, curr) => {
const sorted = [...curr].sort((a, b) => {
return ordering.filter((v) => v[0] === a && v[1] === b).length === 0
? 1
: -1;
});
if (sorted.join(",") !== curr.join(",")) {
return coll + parseInt(sorted[Math.floor(curr.length / 2)], 10);
}
return coll;
}, 0);
})(),
printTime(now.instant().since(timer))
);