92 lines
2.3 KiB
TypeScript
92 lines
2.3 KiB
TypeScript
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))
|
|
);
|