mirror of
https://github.com/ershisan99/advent-of-code.git
synced 2025-12-17 20:49:29 +00:00
2024 day 11 final
This commit is contained in:
@@ -1,35 +1,57 @@
|
||||
import { Worker } from "node:worker_threads";
|
||||
const cache = new Map<string, number>();
|
||||
|
||||
export async function part1(input: string) {
|
||||
export function part1(input: string) {
|
||||
const lines = input.split("\n");
|
||||
const line = lines[0];
|
||||
const stones = line.split(" ").map(Number);
|
||||
stones.length = 1;
|
||||
// for (let i = 0; i < 75; i++) {
|
||||
// console.log(i);
|
||||
// stones = blink(stones);
|
||||
// }
|
||||
let final = 0;
|
||||
await Promise.all(
|
||||
stones.map(async (stone) => {
|
||||
const sum = (await new Promise((res) => {
|
||||
const worker = new Worker("./2024/day-11/workers.ts", {
|
||||
workerData: stone,
|
||||
});
|
||||
|
||||
worker.on("message", (result) => {
|
||||
res(result);
|
||||
});
|
||||
})) as number;
|
||||
final += sum;
|
||||
}),
|
||||
);
|
||||
|
||||
return final;
|
||||
let total = 0;
|
||||
for (const stone of stones) {
|
||||
total += count(stone, 25);
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
export function part2(input: string) {
|
||||
const lines = input.split("\n");
|
||||
const final = 0;
|
||||
return final;
|
||||
const line = lines[0];
|
||||
const stones = line.split(" ").map(Number);
|
||||
let total = 0;
|
||||
for (const stone of stones) {
|
||||
total += count(stone, 75);
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
function count(stone: number, steps: number): number {
|
||||
const key = `${stone},${steps}`;
|
||||
|
||||
if (cache.has(key)) {
|
||||
return cache.get(key) as number;
|
||||
}
|
||||
|
||||
if (steps === 0) {
|
||||
const res = 1;
|
||||
cache.set(key, res);
|
||||
return res;
|
||||
}
|
||||
if (stone === 0) {
|
||||
const res = count(1, steps - 1);
|
||||
cache.set(key, res);
|
||||
return res;
|
||||
}
|
||||
const numberAsString = stone.toString();
|
||||
const numberOfDigits = numberAsString.length;
|
||||
if (numberOfDigits % 2 === 0) {
|
||||
const middle = numberOfDigits / 2;
|
||||
const left = numberAsString.slice(0, middle);
|
||||
const right = numberAsString.slice(middle);
|
||||
const res =
|
||||
count(Number.parseInt(left, 10), steps - 1) +
|
||||
count(Number.parseInt(right, 10), steps - 1);
|
||||
cache.set(key, res);
|
||||
return res;
|
||||
}
|
||||
const res = count(stone * 2024, steps - 1);
|
||||
cache.set(key, res);
|
||||
return res;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user