-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday22.ts
87 lines (67 loc) · 1.65 KB
/
day22.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
81
82
83
84
85
86
87
import { input } from './input';
const mySecrets = input.split('\n').map(BigInt);
const cache = new Map<bigint, bigint>();
function hash(secret: bigint) {
const result = cache.get(secret);
if (result != null) {
return result;
}
const input = secret;
// step 1
let a = secret * 64n;
secret = secret ^ a;
secret = secret % 16777216n;
// step 2
let b = secret / 32n;
secret = secret ^ b;
secret = secret % 16777216n;
// step 3
let c = secret * 2048n;
secret = secret ^ c;
secret = secret % 16777216n;
cache.set(input, secret);
return secret;
}
function part1(secrest: bigint[]) {
return secrest.reduce((a, c) => {
for (let i = 0; i < 2000; i++) {
c = hash(c);
}
return a + c;
}, 0n);
}
function part2(secrest: bigint[]) {
let result = 0n;
const seqCnt = new Map<string, number>();
for (let c of secrest) {
// track sequences while generating
const seqTrack = new Set<string>();
let lastPrice = c;
let sequence = [];
for (let i = 0; i <= 2000; i++) {
c = hash(c);
const price = c % 10n;
const diff = price - lastPrice;
lastPrice = price;
sequence.push(diff);
if (sequence.length > 4) {
sequence.shift();
}
if (sequence.length === 4) {
const key = sequence.join(',');
if (!seqTrack.has(key)) {
seqTrack.add(key);
const cnt = (seqCnt.get(key) ?? 0) + Number(price);
seqCnt.set(key, cnt);
}
}
}
}
let maxVal = 0;
for (let v of seqCnt.values()) {
maxVal = Math.max(maxVal, v);
}
return maxVal;
}
console.log(part1(mySecrets));
console.log(part2(mySecrets));