63 lines
1.6 KiB
TypeScript
63 lines
1.6 KiB
TypeScript
import fs from "node:fs";
|
|
import { printTime, now, toNum } from "../util";
|
|
|
|
const test = false;
|
|
|
|
const data = fs.readFileSync(
|
|
test ? "./inputs/testinput" : "./inputs/input",
|
|
"utf8"
|
|
);
|
|
|
|
let stones = data
|
|
.split("\n")
|
|
.slice(0, -1)[0]
|
|
.split(" ")
|
|
.reduce((stones, stone) => {
|
|
stones[stone] = 1;
|
|
return stones;
|
|
}, {});
|
|
|
|
const iterate = (
|
|
stones: Record<string, number>,
|
|
blinks: number
|
|
): Record<string, number> => {
|
|
for (let index = 0; index < blinks; index++) {
|
|
let newStones = {
|
|
"1": stones["0"] ? stones["0"] : 0,
|
|
};
|
|
Object.entries(stones).forEach(([stone, count]) => {
|
|
if (stone.length % 2 === 0) {
|
|
let stoneA = toNum(stone.slice(0, stone.length / 2)).toString();
|
|
let stoneB = toNum(stone.slice(stone.length / 2)).toString();
|
|
newStones[stoneA]
|
|
? (newStones[stoneA] += count)
|
|
: (newStones[stoneA] = count);
|
|
newStones[stoneB]
|
|
? (newStones[stoneB] += count)
|
|
: (newStones[stoneB] = count);
|
|
} else if (stone !== "0") {
|
|
let newStone = (toNum(stone) * 2024).toString();
|
|
newStones[newStone]
|
|
? (newStones[newStone] += count)
|
|
: (newStones[newStone] = count);
|
|
}
|
|
});
|
|
stones = newStones;
|
|
}
|
|
return stones;
|
|
};
|
|
|
|
let timer = now.instant();
|
|
console.log(
|
|
"part one:",
|
|
Object.values(iterate(stones, 25)).reduce((total, curr) => total + curr, 0),
|
|
printTime(now.instant().since(timer))
|
|
);
|
|
|
|
timer = now.instant();
|
|
console.log(
|
|
"part two:",
|
|
Object.values(iterate(stones, 75)).reduce((total, curr) => total + curr, 0),
|
|
printTime(now.instant().since(timer))
|
|
);
|