-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
80 lines (66 loc) · 1.66 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import {
INPUT_PATH,
runner,
SAMPLE_PATH,
splitLines,
} from '../../../lib/utils';
const path = `${__dirname}/${INPUT_PATH}`;
const MAX = 2000;
const MOD = 16777216;
const MASK = 0xffffff;
const mix = (secret: number, val: number) => ((secret ^ val) & MASK) % MOD;
const getSecret = (secret: number) => {
const s1 = mix(secret, secret << 6);
const s2 = mix(s1, s1 >> 5);
return mix(s2, s2 << 11);
};
const solution1 = (input: string) => {
return splitLines(input)
.map(Number)
.map((secret) => {
let final = secret;
for (let i = 0; i < MAX; i++) {
final = getSecret(final);
}
return final;
})
.reduce((acc, curr) => (acc += curr), 0);
};
const solution2 = (input: string) => {
const diffs: Record<string, number> = {};
splitLines(input)
.map(Number)
.forEach((secret) => {
let final = secret;
let last = secret % 10;
const keysCache: Record<string, boolean> = {};
const key: string[] = [];
for (let i = 0; i < 2000; i++) {
final = getSecret(final);
const price = final % 10;
const diff = price - last;
last = price;
key.push(diff.toString());
const keyStr = key.join('');
if (keysCache[keyStr]) {
key.shift();
continue;
}
if (key.length > 3) {
if (!diffs[keyStr]) diffs[keyStr] = 0;
diffs[keyStr] += price;
keysCache[keyStr] = true;
key.shift();
}
}
});
return Math.max(...Object.values(diffs));
};
runner({
path,
solution: (input) => solution1(input),
});
runner({
path,
solution: (input) => solution2(input),
});