2017 / Day 15
Dueling Generators
Read the original puzzle on adventofcode.com ↗
The solution
solution.c
1#include "aoc.h"
2
3/* 2017 day 15. The modulus is 2^31-1, so the next value is the
4 * product's low 31 bits plus its high bits, never a division. Part
5 * 1 counts low-16 matches over a fixed 40 million pairs. Part 2
6 * keeps only the values divisible by 4 and by 8, compacted into two
7 * rings in unrolled batches, and compares a fixed five million of
8 * those.
9 *
10 * The seeds are the story's positive integers strictly below the
11 * modulus, one on each "Generator A/B starts with " line. "bad
12 * input", "expected integer", "integer exceeds cap", "trailing
13 * input", or "bad seed" otherwise.
14 *
15 * Bounds: SEEDMAX = 2147483646. Part 1 is ROUNDS passes of 32 pairs.
16 * Part 2 fills a RING of 128, FILL at a time, stops at PAIRS, and
17 * refuses a filter that has not produced them after BUDGET batches
18 * ("generator budget exceeded").
19 *
20 * The real file is two seeds, 873 and 583, both far under the modulus. The
21 * generators and the pair counts are the rest of the story. There is no
22 * further input to bound.
23 */
24
25enum { SEEDMAX = 2147483646 };
26
27enum { RING = 128, FILL = 64 };
28
29enum { BUDGET = 2000000 };
30
31enum { ROUNDS = 1250000 };
32
33enum { PAIRS = 5000000 };
34
35typedef struct {
36 slice s;
37 size_t i;
38} Parser;
39
40static int space(uint8_t c) {
41 return c == ' ' || c == '\t' || c == '\r' || c == '\n';
42}
43
44static void ws(Parser *p) {
45 while (p->i < p->s.l && space(p->s.p[p->i])) {
46 p->i++;
47 }
48}
49
50static void text(Parser *p, const char *s) {
51 size_t n = strlen(s);
52 aoc_assert(n <= p->s.l - p->i && !memcmp(p->s.p + p->i, s, n), "bad input");
53 p->i += n;
54}
55
56static int64_t number(Parser *p, int64_t cap) {
57 int neg = 0;
58 int64_t v = 0;
59 if (p->i < p->s.l && (p->s.p[p->i] == '-' || p->s.p[p->i] == '+')) {
60 neg = p->s.p[p->i++] == '-';
61 }
62 size_t start = p->i;
63 while (p->i < p->s.l && p->s.p[p->i] >= '0' && p->s.p[p->i] <= '9') {
64 int d = p->s.p[p->i++] - '0';
65 aoc_assert(v <= (cap - d) / 10 && d <= cap, "integer exceeds cap");
66 v = v * 10 + d;
67 }
68 aoc_assert(p->i > start, "expected integer");
69 return neg ? -v : v;
70}
71
72static void finish(Parser *p) {
73 ws(p);
74 aoc_assert(p->i == p->s.l, "trailing input");
75}
76
77static inline __attribute__((always_inline)) uint32_t next(uint32_t x,
78 uint32_t factor) {
79 uint64_t p = (uint64_t)x * factor;
80 uint32_t v = (uint32_t)((p & 2147483647) + (p >> 31));
81 return v - 2147483647U * (v >= 2147483647U);
82}
83
84static void load(slice in, uint32_t *a, uint32_t *b) {
85 Parser p = {in, 0};
86 text(&p, "Generator A starts with ");
87 int64_t x = number(&p, SEEDMAX);
88 ws(&p);
89 text(&p, "Generator B starts with ");
90 int64_t y = number(&p, SEEDMAX);
91 finish(&p);
92 aoc_assert(x > 0 && y > 0, "bad seed");
93 *a = (uint32_t)x;
94 *b = (uint32_t)y;
95}
96
97slice part1(slice in) {
98 uint32_t a, b;
99 load(in, &a, &b);
100 int count = 0;
101#define PAIR \
102 a = next(a, 16807); \
103 b = next(b, 48271); \
104 count += ((a & 65535) == (b & 65535))
105 for (int i = 0; i < ROUNDS; i++) {
106 PAIR;
107 PAIR;
108 PAIR;
109 PAIR;
110 PAIR;
111 PAIR;
112 PAIR;
113 PAIR;
114 PAIR;
115 PAIR;
116 PAIR;
117 PAIR;
118 PAIR;
119 PAIR;
120 PAIR;
121 PAIR;
122 PAIR;
123 PAIR;
124 PAIR;
125 PAIR;
126 PAIR;
127 PAIR;
128 PAIR;
129 PAIR;
130 PAIR;
131 PAIR;
132 PAIR;
133 PAIR;
134 PAIR;
135 PAIR;
136 PAIR;
137 PAIR;
138 }
139#undef PAIR
140 return slice_from_i64(count);
141}
142
143slice part2(slice in) {
144 uint32_t A, B, a[RING], b[RING];
145 load(in, &A, &B);
146 int ha = 0, hb = 0, ta = 0, tb = 0, na = 0, nb = 0, done = 0, count = 0,
147 work = 0;
148/* Branch-free compaction of batches avoids a loop/branch hook for every
149 * rejected value. */
150#define GEN(v, f, mask, q, t, n) \
151 do { \
152 v = next(v, f); \
153 q[t] = v; \
154 int yes = ((v & (mask)) == 0); \
155 t = (t + yes) & (RING - 1); \
156 n += yes; \
157 } while (0)
158 while (done < PAIRS) {
159 aoc_assert(++work <= BUDGET, "generator budget exceeded");
160 if (na < FILL) {
161 GEN(A, 16807, 3, a, ta, na);
162 GEN(A, 16807, 3, a, ta, na);
163 GEN(A, 16807, 3, a, ta, na);
164 GEN(A, 16807, 3, a, ta, na);
165 GEN(A, 16807, 3, a, ta, na);
166 GEN(A, 16807, 3, a, ta, na);
167 GEN(A, 16807, 3, a, ta, na);
168 GEN(A, 16807, 3, a, ta, na);
169 GEN(A, 16807, 3, a, ta, na);
170 GEN(A, 16807, 3, a, ta, na);
171 GEN(A, 16807, 3, a, ta, na);
172 GEN(A, 16807, 3, a, ta, na);
173 GEN(A, 16807, 3, a, ta, na);
174 GEN(A, 16807, 3, a, ta, na);
175 GEN(A, 16807, 3, a, ta, na);
176 GEN(A, 16807, 3, a, ta, na);
177 GEN(A, 16807, 3, a, ta, na);
178 GEN(A, 16807, 3, a, ta, na);
179 GEN(A, 16807, 3, a, ta, na);
180 GEN(A, 16807, 3, a, ta, na);
181 GEN(A, 16807, 3, a, ta, na);
182 GEN(A, 16807, 3, a, ta, na);
183 GEN(A, 16807, 3, a, ta, na);
184 GEN(A, 16807, 3, a, ta, na);
185 GEN(A, 16807, 3, a, ta, na);
186 GEN(A, 16807, 3, a, ta, na);
187 GEN(A, 16807, 3, a, ta, na);
188 GEN(A, 16807, 3, a, ta, na);
189 GEN(A, 16807, 3, a, ta, na);
190 GEN(A, 16807, 3, a, ta, na);
191 GEN(A, 16807, 3, a, ta, na);
192 GEN(A, 16807, 3, a, ta, na);
193 GEN(A, 16807, 3, a, ta, na);
194 GEN(A, 16807, 3, a, ta, na);
195 GEN(A, 16807, 3, a, ta, na);
196 GEN(A, 16807, 3, a, ta, na);
197 GEN(A, 16807, 3, a, ta, na);
198 GEN(A, 16807, 3, a, ta, na);
199 GEN(A, 16807, 3, a, ta, na);
200 GEN(A, 16807, 3, a, ta, na);
201 GEN(A, 16807, 3, a, ta, na);
202 GEN(A, 16807, 3, a, ta, na);
203 GEN(A, 16807, 3, a, ta, na);
204 GEN(A, 16807, 3, a, ta, na);
205 GEN(A, 16807, 3, a, ta, na);
206 GEN(A, 16807, 3, a, ta, na);
207 GEN(A, 16807, 3, a, ta, na);
208 GEN(A, 16807, 3, a, ta, na);
209 GEN(A, 16807, 3, a, ta, na);
210 GEN(A, 16807, 3, a, ta, na);
211 GEN(A, 16807, 3, a, ta, na);
212 GEN(A, 16807, 3, a, ta, na);
213 GEN(A, 16807, 3, a, ta, na);
214 GEN(A, 16807, 3, a, ta, na);
215 GEN(A, 16807, 3, a, ta, na);
216 GEN(A, 16807, 3, a, ta, na);
217 GEN(A, 16807, 3, a, ta, na);
218 GEN(A, 16807, 3, a, ta, na);
219 GEN(A, 16807, 3, a, ta, na);
220 GEN(A, 16807, 3, a, ta, na);
221 GEN(A, 16807, 3, a, ta, na);
222 GEN(A, 16807, 3, a, ta, na);
223 GEN(A, 16807, 3, a, ta, na);
224 GEN(A, 16807, 3, a, ta, na);
225 }
226 if (nb < FILL) {
227 GEN(B, 48271, 7, b, tb, nb);
228 GEN(B, 48271, 7, b, tb, nb);
229 GEN(B, 48271, 7, b, tb, nb);
230 GEN(B, 48271, 7, b, tb, nb);
231 GEN(B, 48271, 7, b, tb, nb);
232 GEN(B, 48271, 7, b, tb, nb);
233 GEN(B, 48271, 7, b, tb, nb);
234 GEN(B, 48271, 7, b, tb, nb);
235 GEN(B, 48271, 7, b, tb, nb);
236 GEN(B, 48271, 7, b, tb, nb);
237 GEN(B, 48271, 7, b, tb, nb);
238 GEN(B, 48271, 7, b, tb, nb);
239 GEN(B, 48271, 7, b, tb, nb);
240 GEN(B, 48271, 7, b, tb, nb);
241 GEN(B, 48271, 7, b, tb, nb);
242 GEN(B, 48271, 7, b, tb, nb);
243 GEN(B, 48271, 7, b, tb, nb);
244 GEN(B, 48271, 7, b, tb, nb);
245 GEN(B, 48271, 7, b, tb, nb);
246 GEN(B, 48271, 7, b, tb, nb);
247 GEN(B, 48271, 7, b, tb, nb);
248 GEN(B, 48271, 7, b, tb, nb);
249 GEN(B, 48271, 7, b, tb, nb);
250 GEN(B, 48271, 7, b, tb, nb);
251 GEN(B, 48271, 7, b, tb, nb);
252 GEN(B, 48271, 7, b, tb, nb);
253 GEN(B, 48271, 7, b, tb, nb);
254 GEN(B, 48271, 7, b, tb, nb);
255 GEN(B, 48271, 7, b, tb, nb);
256 GEN(B, 48271, 7, b, tb, nb);
257 GEN(B, 48271, 7, b, tb, nb);
258 GEN(B, 48271, 7, b, tb, nb);
259 GEN(B, 48271, 7, b, tb, nb);
260 GEN(B, 48271, 7, b, tb, nb);
261 GEN(B, 48271, 7, b, tb, nb);
262 GEN(B, 48271, 7, b, tb, nb);
263 GEN(B, 48271, 7, b, tb, nb);
264 GEN(B, 48271, 7, b, tb, nb);
265 GEN(B, 48271, 7, b, tb, nb);
266 GEN(B, 48271, 7, b, tb, nb);
267 GEN(B, 48271, 7, b, tb, nb);
268 GEN(B, 48271, 7, b, tb, nb);
269 GEN(B, 48271, 7, b, tb, nb);
270 GEN(B, 48271, 7, b, tb, nb);
271 GEN(B, 48271, 7, b, tb, nb);
272 GEN(B, 48271, 7, b, tb, nb);
273 GEN(B, 48271, 7, b, tb, nb);
274 GEN(B, 48271, 7, b, tb, nb);
275 GEN(B, 48271, 7, b, tb, nb);
276 GEN(B, 48271, 7, b, tb, nb);
277 GEN(B, 48271, 7, b, tb, nb);
278 GEN(B, 48271, 7, b, tb, nb);
279 GEN(B, 48271, 7, b, tb, nb);
280 GEN(B, 48271, 7, b, tb, nb);
281 GEN(B, 48271, 7, b, tb, nb);
282 GEN(B, 48271, 7, b, tb, nb);
283 GEN(B, 48271, 7, b, tb, nb);
284 GEN(B, 48271, 7, b, tb, nb);
285 GEN(B, 48271, 7, b, tb, nb);
286 GEN(B, 48271, 7, b, tb, nb);
287 GEN(B, 48271, 7, b, tb, nb);
288 GEN(B, 48271, 7, b, tb, nb);
289 GEN(B, 48271, 7, b, tb, nb);
290 GEN(B, 48271, 7, b, tb, nb);
291 }
292 int n = na < nb ? na : nb;
293 if (n > PAIRS - done) {
294 n = PAIRS - done;
295 }
296 for (int i = 0; i < n; i++) {
297 count += ((a[ha] & 65535) == (b[hb] & 65535));
298 ha = (ha + 1) & (RING - 1);
299 hb = (hb + 1) & (RING - 1);
300 }
301 na -= n;
302 nb -= n;
303 done += n;
304 }
305#undef GEN
306 return slice_from_i64(count);
307}
308
309const struct aoc_method aoc_methods[] = {
310 {0, 0},
311};aoc.h
1#ifndef AOC_H
2#define AOC_H
3
4#include <stdarg.h>
5#include <stddef.h>
6#include <stdint.h>
7#include <stdlib.h>
8#include <string.h>
9
10/* The only required boundary between infra and a solution.
11 * `input` is read-only and is not owned by the solution.
12 * The returned slice is allocated with malloc. It is the only
13 * block still live when the function returns. Infra copies it
14 * and then frees it.
15 */
16typedef struct {
17 uint8_t *p;
18 size_t l;
19} slice;
20
21/* p is null and l is 0. Infra uses this when a run has no output. */
22static const slice empty_slice = {0};
23
24typedef slice (*aoc_fn)(slice);
25
26/* One named method. The name is a C identifier, at most 31
27 * characters, and it is the URL suffix: /YYYY/D/P/<name>.
28 * estimate and span are examples, not a fixed list. A day
29 * exports as many as it wants. The array ends with {0, 0}.
30 * part1 and part2 are not entries in this list.
31 */
32struct aoc_method {
33 const char *name;
34 aoc_fn fn;
35};
36
37slice part1(slice input);
38slice part2(slice input);
39
40extern const struct aoc_method aoc_methods[];
41
42/* Provided by the runtime. Records msg and returns. */
43void aoc_fail(const char *msg);
44
45/* Stops the run when cond is false and reports msg. */
46_Noreturn void aoc_assert_fail(const char *msg);
47#ifndef aoc_assert
48#define aoc_assert(cond, msg) \
49 do { \
50 if (!(cond)) { \
51 aoc_assert_fail(msg); \
52 } \
53 } while (0)
54#endif
55
56/* Decimal text of a uint64_t is at most 20 digits. A sign and a
57 * little spare fit here. Size a number buffer from this.
58 */
59enum { AOC_I64_TEXT = 32 };
60
61/* Decimal digits of v. No sign. d has room for 20 digits. */
62static inline char *aoc_u64_text(char *d, uint64_t v) {
63 char tmp[AOC_I64_TEXT];
64 char *end = tmp + AOC_I64_TEXT;
65 char *p = end;
66 size_t n;
67 do {
68 *--p = (char)('0' + (v % 10ull));
69 v /= 10ull;
70 } while (v);
71 n = (size_t)(end - p);
72 memcpy(d, p, n);
73 return d + n;
74}
75
76/* Decimal digits of v. The minimum int64_t is not negated. */
77static inline char *aoc_i64_text(char *d, int64_t v) {
78 uint64_t u;
79 if (v < 0) {
80 *d++ = '-';
81 u = (uint64_t)(-(v + 1)) + 1ull;
82 } else {
83 u = (uint64_t)v;
84 }
85 return aoc_u64_text(d, u);
86}
87
88/* n values, one space between them. The author knows the order. */
89static inline char *aoc_u64s(char *d, const uint64_t *v, size_t n) {
90 size_t i;
91 for (i = 0; i < n; i++) {
92 if (i) {
93 *d++ = ' ';
94 }
95 d = aoc_u64_text(d, v[i]);
96 }
97 return d;
98}
99
100static inline char *aoc_i64s(char *d, const int64_t *v, size_t n) {
101 size_t i;
102 for (i = 0; i < n; i++) {
103 if (i) {
104 *d++ = ' ';
105 }
106 d = aoc_i64_text(d, v[i]);
107 }
108 return d;
109}
110
111static inline char *aoc_ints(char *d, const int *v, size_t n) {
112 size_t i;
113 for (i = 0; i < n; i++) {
114 if (i) {
115 *d++ = ' ';
116 }
117 d = aoc_i64_text(d, (int64_t)v[i]);
118 }
119 return d;
120}
121
122/* Write fmt at buf. Return the cursor for the next call.
123 * %d takes int. %i takes int64_t. %u takes uint64_t.
124 * %s takes a C string. %% is a percent sign.
125 * A literal run is memcpy.
126 * %D takes (int *, size_t). %I takes (int64_t *, size_t).
127 * %U takes (uint64_t *, size_t). One space between values.
128 */
129static inline char *aoc_vprintf(const char *fmt, char *buf, va_list ap) {
130 while (*fmt) {
131 const char *lit = fmt;
132 size_t n;
133 while (*fmt && *fmt != '%') {
134 fmt++;
135 }
136 n = (size_t)(fmt - lit);
137 if (n) {
138 memcpy(buf, lit, n);
139 buf += n;
140 }
141 if (*fmt != '%') {
142 break;
143 }
144 fmt++;
145 if (*fmt == '%') {
146 *buf++ = '%';
147 fmt++;
148 continue;
149 }
150 if (*fmt == 's') {
151 const char *s = va_arg(ap, const char *);
152 n = strlen(s);
153 if (n) {
154 memcpy(buf, s, n);
155 buf += n;
156 }
157 fmt++;
158 continue;
159 }
160 if (*fmt == 'd') {
161 buf = aoc_i64_text(buf, (int64_t)va_arg(ap, int));
162 fmt++;
163 continue;
164 }
165 if (*fmt == 'i') {
166 buf = aoc_i64_text(buf, va_arg(ap, int64_t));
167 fmt++;
168 continue;
169 }
170 if (*fmt == 'u') {
171 buf = aoc_u64_text(buf, va_arg(ap, uint64_t));
172 fmt++;
173 continue;
174 }
175 if (*fmt == 'D') {
176 const int *v = va_arg(ap, int *);
177 buf = aoc_ints(buf, v, va_arg(ap, size_t));
178 fmt++;
179 continue;
180 }
181 if (*fmt == 'I') {
182 const int64_t *v = va_arg(ap, int64_t *);
183 buf = aoc_i64s(buf, v, va_arg(ap, size_t));
184 fmt++;
185 continue;
186 }
187 if (*fmt == 'U') {
188 const uint64_t *v = va_arg(ap, uint64_t *);
189 buf = aoc_u64s(buf, v, va_arg(ap, size_t));
190 fmt++;
191 continue;
192 }
193 aoc_assert(0, "bad format");
194 }
195 return buf;
196}
197
198static inline char *aoc_printf(const char *fmt, char *buf, ...) {
199 va_list ap;
200 va_start(ap, buf);
201 buf = aoc_vprintf(fmt, buf, ap);
202 va_end(ap);
203 return buf;
204}
205
206/* Copy n bytes of text into a malloc'd slice. */
207static inline slice slice_from_text(const char *s, size_t n) {
208 uint8_t *p = malloc(n);
209 aoc_assert(p, "out of memory");
210 if (n) {
211 memcpy(p, s, n);
212 }
213 return (slice){p, n};
214}
215
216/* Decimal text of v, allocated at AOC_I64_TEXT. The minimum
217 * int64_t is not negated. slice.l is the bytes written.
218 */
219static inline slice slice_from_i64(int64_t v) {
220 char tmp[AOC_I64_TEXT];
221 char *d;
222 uint8_t *p;
223 size_t n;
224 d = aoc_printf("%i", tmp, v);
225 n = (size_t)(d - tmp);
226 p = malloc(AOC_I64_TEXT);
227 aoc_assert(p, "out of memory");
228 memcpy(p, tmp, n);
229 return (slice){p, n};
230}
231
232/* Parse one decimal slice into *out. A leading '-' is allowed.
233 * Returns 1 on success, 0 for invalid text or int64_t overflow.
234 */
235static inline int slice_to_i64(slice s, int64_t *out) {
236 size_t i = 0;
237 int neg = 0;
238 uint64_t u = 0;
239 if (!s.p || s.l == 0 || !out) {
240 return 0;
241 }
242 if (s.p[0] == '-') {
243 neg = 1;
244 i = 1;
245 if (s.l == 1) {
246 return 0;
247 }
248 }
249 for (; i < s.l; i++) {
250 uint8_t c = s.p[i];
251 if (c < '0' || c > '9') {
252 return 0;
253 }
254 uint64_t digit = (uint64_t)(c - '0');
255 uint64_t limit = (uint64_t)INT64_MAX + (uint64_t)neg;
256 if (u > (limit - digit) / 10u) {
257 return 0;
258 }
259 u = u * 10u + digit;
260 }
261 if (neg) {
262 *out = u == (uint64_t)INT64_MAX + 1u ? INT64_MIN : -(int64_t)u;
263 } else {
264 *out = (int64_t)u;
265 }
266 return 1;
267}
268
269#endifThe aha moment
Forty million pairs from two starting numbers. That sounds disproportionate until we count the work: each pair needs two multiplications, two remainders, a comparison, and perhaps an increment. There is no search tree, no growing collection, and no expensive object to construct. A tight loop is a sensible first solution. The challenge is to resist making each of those eighty million generator advances unnecessarily elaborate.
The long binary examples are there to explain the comparison, not to request binary strings. Keeping the lowest sixteen bits means applying a mask of 65,535. Compare the two masked integers. Also advance both generators before the first comparison: the supplied seeds are previous values, not the first pair sent to the judge. The example's first five pairs, with exactly one match, are a much friendlier place to catch that mistake than a forty-million-pair run.
There is one arithmetic hazard worth noticing early. Each generated value fits below 2,147,483,647, but multiplying it by 48,271 can produce a value around 104 trillion. The product needs a wider integer even though the remainder fits in 31 bits. The local seeds, 873 and 583, do not change that requirement; small starting values do not keep the later sequence small.
If the plain loop needs help, the modulus offers it. It is 2^31 - 1. Split a product into high bits times 2^31 plus its low 31 bits. Modulo this number, 2^31 behaves like one, so adding the high and low pieces gives the same remainder. With these factors the sum is less than twice the modulus; at most one subtraction finishes the reduction. That little identity replaces division without changing the sequence. It is an optimization of a justified simulation, not a magical shortcut that avoids generating the values.
Part two lowers the count to five million. Relief—until we read what counts as a pair. A keeps only multiples of four, B only multiples of eight, and each advances independently. We must compare the first acceptable A with the first acceptable B, even if they came from very different positions in their original streams. Advancing both together and discarding a pair when either fails would answer a different question.
The simplest correct loop waits for A to pass its filter, then waits for B, then compares. Roughly one A in four and one B in eight should qualify, suggesting about twenty million A advances and forty million B advances. That is a planning estimate, not a promise about every prefix. Five million accepted pairs still mean roughly sixty million advances: the smaller headline number has hidden most of the work.
The implementation keeps the same logic but generates small batches, preserving accepted values in two queues until they can be paired. The queues have 128 slots each and refill in batches of 64; they do not store either full sequence. Part one runs exactly forty million pairs. Part two stops at five million accepted pairs or explicitly rejects after two million batch iterations. Seeds must be positive and strictly below the modulus. These bounds keep the brute-force work finite, while the arithmetic identity and batching make each step cheap.
See also
Categories for 2015–2024 adapted from u/Boojum’s 500 Stars: A Categorization and Mega-Guide ↗. A day can belong to several categories. Tags from 2025 onward are our additions.
Try your input
One POST, one reply. Your input is not saved.