diff --git a/src/2024/day11.js b/src/2024/day11.js index 1b166e55..40975dc3 100644 --- a/src/2024/day11.js +++ b/src/2024/day11.js @@ -13,46 +13,26 @@ function next(stone) { } const memory = new Map(); -function do25(stone) { - if (memory.has(stone)) return memory.get(stone); - let stones = [stone]; - for (let j = 0; j < 25; j++) stones = stones.flatMap(next); - memory.set(stone, stones); - return stones; -} - -// function doit(stone, times = 25) { -// if (times === 0) return 1; +function doit(stone, times) { + if (times === 0) return 1; -// const key = `${stone},${times}`; -// if (memory.has(key)) return memory.get(key); -// let sum = 0; -// let stones = next(stone); -// stones.forEach(stone => { -// sum += doit(stone, times - 1); -// }); -// memory.set(key, sum); -// return sum; -// } - -export function part1(input) { - let stones = input.split(" ").map(Number); + const key = `${stone},${times}`; + if (memory.has(key)) return memory.get(key); let sum = 0; + let stones = next(stone); stones.forEach(stone => { - sum += do25(stone).length; + sum += doit(stone, times - 1); }); + memory.set(key, sum); return sum; } +export function part1(input) { + let stones = input.split(" ").map(Number); + return stones.reduce((sum, stone) => sum + doit(stone, 25), 0); +} + export function part2(input) { let stones = input.split(" ").map(Number); - let sum = 0; - stones.forEach(stone => { - do25(stone).forEach(stone => { - do25(stone).forEach(stone => { - sum += do25(stone).length; - }); - }); - }); - return sum; + return stones.reduce((sum, stone) => sum + doit(stone, 75), 0); }