Skip to content

Commit b310894

Browse files
committed
refactor
1 parent 28c9f78 commit b310894

File tree

1 file changed

+12
-9
lines changed

1 file changed

+12
-9
lines changed

src/2024/day22.js

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -14,22 +14,25 @@ export function part1(input) {
1414
export function part2(input) {
1515
let numbers = input.split("\n").map(BigInt);
1616
let cache = new Map();
17+
let max = 0;
1718
for (let prev of numbers) {
1819
let visited = new Set();
1920
let diffs = [];
2021
for (let i = 0; i < 2000; i++) {
2122
let next = hash(prev);
2223
diffs.push(Number((next % 10n) - (prev % 10n)));
2324
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);
30-
}
31-
}
25+
if (diffs.length < 4) continue;
26+
27+
let key = diffs.join(",");
28+
diffs.shift();
29+
if (visited.has(key)) continue;
30+
31+
let sum = (cache.get(key) || 0) + Number(next % 10n);
32+
max = Math.max(max, sum);
33+
cache.set(key, sum);
34+
visited.add(key);
3235
}
3336
}
34-
return Math.max(...cache.values());
37+
return max;
3538
}

0 commit comments

Comments
 (0)