Skip to content

Commit 28c9f78

Browse files
committed
optimized runtime to 1 second
1 parent e796a21 commit 28c9f78

File tree

1 file changed

+14
-17
lines changed

1 file changed

+14
-17
lines changed

src/2024/day22.js

Lines changed: 14 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -13,26 +13,23 @@ export function part1(input) {
1313

1414
export function part2(input) {
1515
let numbers = input.split("\n").map(BigInt);
16-
let diffs = numbers.map(() => []);
1716
let cache = new Map();
18-
let max = 0;
19-
for (let i = 0; i < 2000; i++) {
20-
numbers = numbers.map((prev, j) => {
17+
for (let prev of numbers) {
18+
let visited = new Set();
19+
let diffs = [];
20+
for (let i = 0; i < 2000; i++) {
2121
let next = hash(prev);
22-
diffs[j].push(Number((next % 10n) - (prev % 10n)));
23-
if (diffs[j].length === 4) {
24-
let key = diffs[j].join(",");
25-
let value = cache.get(key) || { sum: 0, set: new Set() };
26-
if (!value.set.has(j)) {
27-
value.set.add(j);
28-
value.sum += Number(next % 10n);
29-
max = Math.max(max, value.sum);
22+
diffs.push(Number((next % 10n) - (prev % 10n)));
23+
prev = next;
24+
if (diffs.length >= 4) {
25+
let key = diffs.slice(-4).join(",");
26+
if (!visited.has(key)) {
27+
let sum = (cache.get(key) || 0) + Number(next % 10n);
28+
cache.set(key, sum);
29+
visited.add(key);
3030
}
31-
cache.set(key, value);
32-
diffs[j].shift();
3331
}
34-
return next;
35-
});
32+
}
3633
}
37-
return max;
34+
return Math.max(...cache.values());
3835
}

0 commit comments

Comments
 (0)