Skip to content

Commit

Permalink
memoized solution
Browse files Browse the repository at this point in the history
  • Loading branch information
shahata committed Dec 11, 2024
1 parent 868a865 commit 59be11b
Showing 1 changed file with 13 additions and 33 deletions.
46 changes: 13 additions & 33 deletions src/2024/day11.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

0 comments on commit 59be11b

Please sign in to comment.