2017 / Day 23

Coprocessor Conflagration

Read the original puzzle on adventofcode.com ↗

The solution

C11

solution.c

1#include "aoc.h"
2
3/* 2017 day 23. The hot loop is a fixed 16-instruction factor search.
4 * When that sequence is present it is not run: b is tested by trial
5 * division, the registers are left as the loop would have left
6 * them, and the multiply count gains (b-2)*(b-2). Anything else,
7 * including the constants and the outer steps, is interpreted, so
8 * the program's own numbers still drive the answer. Part 1 returns
9 * the multiply count; part 2 sets a to 1 and returns h.
10 *
11 * Opcodes are set, sub, mul, and jnz, on registers a-h, with literals at
12 * most LITMAX. "bad opcode", "bad destination", "missing operand",
13 * "bad input", "expected integer", "integer exceeds cap", "trailing
14 * input", "empty program", or "too many instructions" otherwise.
15 * The replacement runs only for b in BMIN..BMAX ("factor loop
16 * exceeds cap" outside it).
17 *
18 * Bounds: PROGMAX instructions and STEPS interpreted steps. Trial
19 * division stops at sqrt(b), and b is at most BMAX, so that
20 * replacement stays a short scan.
21 *
22 * The real program is 32 lines and can be read straight through. It sets b to
23 * 67. When a is nonzero it rewrites b to 106700 and c to 123700, then steps b
24 * by 17, one thousand and one values. The inner 16 instructions set d and e to
25 * 2 and test whether d*e equals b. Every such b sits inside BMIN..BMAX. h
26 * counts the composites.
27 */
28
29enum { PROGMAX = 256 };
30
31enum { LITMAX = 1000000000 };
32
33enum { STEPS = 2000000 };
34
35enum { BMIN = 3, BMAX = 1000000 };
36
37static const int64_t REGCAP = 1000000000000LL;
38
39typedef struct {
40    slice s;
41    size_t i;
42} Parser;
43
44static int space(uint8_t c) {
45    return c == ' ' || c == '\t' || c == '\r' || c == '\n';
46}
47
48static void ws(Parser *p) {
49    while (p->i < p->s.l && space(p->s.p[p->i])) {
50        p->i++;
51    }
52}
53
54static void text(Parser *p, const char *s) {
55    size_t n = strlen(s);
56    aoc_assert(n <= p->s.l - p->i && !memcmp(p->s.p + p->i, s, n), "bad input");
57    p->i += n;
58}
59
60static int64_t number(Parser *p, int64_t cap) {
61    int neg = 0;
62    int64_t v = 0;
63    if (p->i < p->s.l && (p->s.p[p->i] == '-' || p->s.p[p->i] == '+')) {
64        neg = p->s.p[p->i++] == '-';
65    }
66    size_t start = p->i;
67    while (p->i < p->s.l && p->s.p[p->i] >= '0' && p->s.p[p->i] <= '9') {
68        int d = p->s.p[p->i++] - '0';
69        aoc_assert(v <= (cap - d) / 10 && d <= cap, "integer exceeds cap");
70        v = v * 10 + d;
71    }
72    aoc_assert(p->i > start, "expected integer");
73    return neg ? -v : v;
74}
75
76static void finish(Parser *p) {
77    ws(p);
78    aoc_assert(p->i == p->s.l, "trailing input");
79}
80
81static slice line(Parser *p) {
82    size_t b = p->i;
83    while (p->i < p->s.l && p->s.p[p->i] != '\n') {
84        p->i++;
85    }
86    size_t e = p->i;
87    if (e > b && p->s.p[e - 1] == '\r') {
88        e--;
89    }
90    if (p->i < p->s.l) {
91        p->i++;
92    }
93    return (slice){b ? p->s.p + b : p->s.p, e - b};
94}
95
96static int64_t absolute(int64_t x) {
97    return x < 0 ? -x : x;
98}
99
100typedef struct {
101    int reg;
102    int64_t v;
103} Arg;
104
105typedef struct {
106    int op;
107    Arg a, b;
108} Ins;
109
110static Ins code[PROGMAX];
111static int n;
112
113static Arg arg(Parser *p) {
114    aoc_assert(p->i < p->s.l, "missing operand");
115    uint8_t c = p->s.p[p->i];
116    if (c >= 'a' && c <= 'h') {
117        p->i++;
118        return (Arg){c - 'a', 0};
119    }
120    return (Arg){-1, number(p, LITMAX)};
121}
122
123static inline __attribute__((always_inline)) int
124identify_coprocessor_opcode(const char *ops[], Parser q, int op) {
125    for (int i = 0; i < 4; i++) {
126        if (q.s.l >= 4 && !memcmp(q.s.p, ops[i], 3) && q.s.p[3] == ' ') {
127            op = i;
128        }
129    }
130
131    return op;
132}
133
134static void load(slice in) {
135    Parser p = {in, 0};
136    n = 0;
137    const char *ops[] = {"set", "sub", "mul", "jnz"};
138    while (p.i < in.l) {
139        Parser q = {line(&p), 0};
140        aoc_assert(n < PROGMAX, "too many instructions");
141        int op = -1;
142        op = identify_coprocessor_opcode(ops, q, op);
143        aoc_assert(op >= 0, "bad opcode");
144        q.i = 4;
145        Ins a = {op, arg(&q), {-1, 0}};
146        text(&q, " ");
147        a.b = arg(&q);
148        finish(&q);
149        aoc_assert(op == 3 || a.a.reg >= 0, "bad destination");
150        code[n++] = a;
151    }
152    aoc_assert(n, "empty program");
153}
154
155static int64_t val(Arg a, int64_t r[8]) {
156    return a.reg < 0 ? a.v : r[a.reg];
157}
158
159static int same(Ins a, int op, int ar, int64_t av, int br, int64_t bv) {
160    return a.op == op && a.a.reg == ar && a.b.reg == br &&
161           (ar >= 0 || a.a.v == av) && (br >= 0 || a.b.v == bv);
162}
163
164static int factor_loop(int pc) {
165    if (pc + 16 > n) {
166        return 0;
167    }
168#define I(k, op, ar, av, br, bv) same(code[pc + k], op, ar, av, br, bv)
169    return I(0, 0, 5, 0, -1, 1) && I(1, 0, 3, 0, -1, 2) &&
170           I(2, 0, 4, 0, -1, 2) && I(3, 0, 6, 0, 3, 0) && I(4, 2, 6, 0, 4, 0) &&
171           I(5, 1, 6, 0, 1, 0) && I(6, 3, 6, 0, -1, 2) &&
172           I(7, 0, 5, 0, -1, 0) && I(8, 1, 4, 0, -1, -1) &&
173           I(9, 0, 6, 0, 4, 0) && I(10, 1, 6, 0, 1, 0) &&
174           I(11, 3, 6, 0, -1, -8) && I(12, 1, 3, 0, -1, -1) &&
175           I(13, 0, 6, 0, 3, 0) && I(14, 1, 6, 0, 1, 0) &&
176           I(15, 3, 6, 0, -1, -13);
177#undef I
178}
179
180static inline __attribute__((always_inline)) int test_composite(int64_t b,
181                                                                int composite) {
182    for (int64_t d = 2; d * d <= b; d++) {
183        if (b % d == 0) {
184            composite = 1;
185            break;
186        }
187    }
188
189    return composite;
190}
191
192static slice solve(slice in, int debug_off) {
193    load(in);
194    int64_t r[8] = {0}, pc = 0, muls = 0;
195    r[0] = debug_off;
196    int work = 0;
197    while (pc >= 0 && pc < n) {
198        aoc_assert(++work <= STEPS, "execution exceeds cap");
199        if (factor_loop((int)pc)) {
200            int64_t b = r[1];
201            aoc_assert(b >= BMIN && b <= BMAX, "factor loop exceeds cap");
202            int composite = 0;
203            composite = test_composite(b, composite);
204            r[3] = r[4] = b;
205            r[5] = !composite;
206            r[6] = 0;
207            aoc_assert(muls <= INT64_MAX - (b - 2) * (b - 2),
208                       "multiply count overflow");
209            muls += (b - 2) * (b - 2);
210            pc += 16;
211            continue;
212        }
213        Ins a = code[pc];
214        int64_t x = val(a.a, r), y = val(a.b, r), v = 0;
215        if (a.op == 3) {
216            pc += x ? y : 1;
217            continue;
218        }
219        if (a.op == 0) {
220            v = y;
221        } else if (a.op == 1) {
222            v = x - y;
223        } else {
224            aoc_assert(!y || absolute(x) <= REGCAP / absolute(y),
225                       "register exceeds cap");
226            v = x * y;
227            muls++;
228        }
229        aoc_assert(absolute(v) <= REGCAP, "register exceeds cap");
230        r[a.a.reg] = v;
231        pc++;
232    }
233    return slice_from_i64(debug_off ? r[7] : muls);
234}
235
236slice part1(slice in) {
237    return solve(in, 0);
238}
239
240slice part2(slice in) {
241    return solve(in, 1);
242}
243
244const struct aoc_method aoc_methods[] = {
245    {0, 0},
246};

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#endif

The aha moment

We have just built a tiny interpreter for Duet. Surely this is another quick reuse: change the instruction set, count multiplications, and run. For part one, that instinct is right. The local program has only 32 instructions and, with every register initially zero, terminates after 34,136 executed instructions. There is no need to understand the whole algorithm before earning that first star.

There is one semantic change to catch: jnz jumps for any nonzero value, including a negative one. Duet's jgz jumped only for positive values. The names are similar enough to make a reused interpreter almost correct, which is a particularly frustrating kind of wrong.

Part two changes a single starting register. Set a to one and the comfortable run becomes an overheating machine. Instead of waiting, trace just the initialization. With a zero, b and c both remain 67. With a one, b becomes 106,700 and c becomes 123,700. At the bottom of the program, b advances by seventeen until it reaches c: 1,001 candidate values. A tiny input edit has opened a much larger computation.

Now read the backward jumps as loops rather than individual instructions. Registers d and e both begin at two. The inner body computes d × e - b and clears flag f when that is zero. It then increments e, looping until e reaches b, and does the same for d. Afterward, h increases if the flag was cleared. This is an extraordinarily laborious way to ask whether b has a nontrivial factor pair.

That understanding also explains part one's multiplication count: at b = 67, the loop tests 65 × 65 pairs. In part two the same shape would test about 13.3 trillion pairs across the progression. Each pair executes at least eight instructions. Even a hypothetical interpreter sustaining ten million instructions per second would spend roughly four months on that work. Making the dispatch loop a little faster is not the useful next move.

The question hidden under the assembly is whether each candidate is composite. If b = d × e with both factors at least two, at least one factor is no greater than the square root of b. Try divisors from two through that square root and stop at the first divisor. Across all 1,001 local candidates, even testing every possible divisor this way takes fewer than 339,000 remainder checks. Most composite candidates stop much earlier. That is the satisfying collapse: months of simulated machinery become a short arithmetic scan.

For a personal solve, translating the verified outer progression and counting composites is enough. The implementation keeps a little more of the original program: it recognizes the complete sixteen-instruction factor loop, replaces only that loop, and interprets everything around it. The input still determines the starting value, endpoint, and increment. The replacement also restores the loop's final registers and adds (b - 2)² to the multiplication count, so it preserves both questions rather than merely returning a known answer.

That shortcut is conditional on the exact loop being present and b lying from three through 1,000,000. Other instructions retain ordinary interpretation, capped at two million executed steps. Programs may contain up to 256 instructions, literals within ±1,000,000,000, and register magnitudes through 10^12. The crucial verification is not that a long run appears stuck; it is that we have identified what the expensive loop computes and replaced it with the same computation.

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.