Skip to content

Commit 3247079

Browse files
committed
solved day 22
1 parent f168464 commit 3247079

File tree

9 files changed

+2215
-67
lines changed

9 files changed

+2215
-67
lines changed

src/2024/day22.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
function hash(n) {
2+
n = (n ^ (n * 64n)) % 16777216n;
3+
n = (n ^ (n / 32n)) % 16777216n;
4+
n = (n ^ (n * 2048n)) % 16777216n;
5+
return n;
6+
}
7+
8+
export function part1(input) {
9+
let numbers = input.split("\n").map(BigInt);
10+
for (let i = 0; i < 2000; i++) numbers = numbers.map(hash);
11+
return numbers.reduce((a, b) => a + b, 0n);
12+
}
13+
14+
export function part2(input) {
15+
let numbers = input.split("\n").map(BigInt);
16+
let diffs = numbers.map(() => []);
17+
let cache = new Map();
18+
let max = 0;
19+
for (let i = 0; i < 2000; i++) {
20+
numbers = numbers.map((prev, j) => {
21+
let next = hash(prev);
22+
diffs[j].push(Number((next % 10n) - (prev % 10n)));
23+
if (diffs[j].length >= 4) {
24+
let key = diffs[j].slice(-4).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);
30+
}
31+
cache.set(key, value);
32+
}
33+
return next;
34+
});
35+
}
36+
return max;
37+
}

src/2024/day22.spec.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import { part1, part2 } from "./day22.js";
2+
import readInput from "../utils/read-input.js";
3+
4+
const input = readInput(import.meta.url);
5+
6+
describe("day22 2024", () => {
7+
describe("part1", () => {
8+
test("it should work for part 1 examples", () => {
9+
expect(part1(["1", "10", "100", "2024"].join("\n"))).toEqual(37327623n);
10+
});
11+
12+
test("it should work for part 1 input", () => {
13+
expect(part1(input)).toEqual(17612566393n);
14+
});
15+
});
16+
17+
describe("part2", () => {
18+
test("it should work for part 2 examples", () => {
19+
expect(part2(["1", "2", "3", "2024"].join("\n"))).toEqual(23);
20+
});
21+
22+
test("it should work for part 2 input", () => {
23+
expect(part2(input)).toEqual(1968);
24+
});
25+
});
26+
});

0 commit comments

Comments
 (0)