-
Notifications
You must be signed in to change notification settings - Fork 0
/
day10.test.ts
197 lines (177 loc) · 2.16 KB
/
day10.test.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
/* === TYPES === */
type Diffs = Record<1 | 3, number>;
/* === PREPARE INPUT === */
export const prepareInput = ([input]: TemplateStringsArray) =>
input.split("\n").map(Number);
/* === UTILS === */
const numCompare = (a: number, b: number) => a - b;
const last = <T>(xs: T[]): T => xs[xs.length - 1];
const empty = (): Diffs => ({ 1: 0, 3: 0 });
const toDiff = (xs: number[]): (1 | 3)[] =>
xs.map((x, i) => (x - (xs[i - 1] || 0)) as 1 | 3);
const product = (a: number, b: number) => a * b;
// Ways of passing x ones in a row
const COMBINATIONS = [1, 1, 2, 4, 7];
const toCombinations = (x: number) => COMBINATIONS[x];
const countOccurences = (xs: (1 | 3)[]) =>
xs.reduce((diffs, x) => {
diffs[x] = diffs[x] + 1;
return diffs;
}, empty());
/* === IMPLEMENTATION === */
const joltageDiff = (adapters: number[]): Diffs => {
const sorted = adapters.sort(numCompare);
const withDevice = [...sorted, last(sorted) + 3];
return countOccurences(toDiff(withDevice));
};
const countCombinations = (adapters: number[]): number =>
toDiff(adapters)
.join("")
.split("3") // get rows of ones in between 3s
.filter(Boolean)
.map((group) => group.length)
.map(toCombinations)
.reduce(product, 1);
/* === TESTS === */
test("Day 10a - test", () => {
const diffs = joltageDiff(testInput);
expect(diffs[1] * diffs[3]).toBe(220);
});
test("Day 10a - prod", () => {
const diffs = joltageDiff(prodInput);
expect(diffs[1] * diffs[3]).toBe(1836);
});
test("Day 10b - test", () => {
const result = countCombinations(testInput);
expect(result).toBe(19208);
});
test("Day 10b - prod", () => {
const result = countCombinations(prodInput);
expect(result).toBe(43406276662336);
});
/* === INPUTS === */
const testInput = prepareInput`28
33
18
42
31
14
46
20
48
47
24
23
49
45
19
38
39
11
1
32
25
35
8
17
7
9
4
2
34
10
3`;
const prodInput = prepareInput`71
30
134
33
51
115
122
38
61
103
21
12
44
129
29
89
54
83
96
91
133
102
99
52
144
82
22
68
7
15
93
125
14
92
1
146
67
132
114
59
72
107
34
119
136
60
20
53
8
46
55
26
126
77
65
78
13
108
142
27
75
110
90
35
143
86
116
79
48
113
101
2
123
58
19
76
16
66
135
64
28
9
6
100
124
47
109
23
139
145
5
45
106
41`;