2016 / Day 12

Leonardo's Monorail

Read the original puzzle on adventofcode.com ↗

The solution

C11

solution.c

1#include "aoc.h"
2
3#include <string.h>
4
5/* 2016 day 12. Assembunny: cpy, inc, dec, jnz on registers a-d.
6 *
7 * The real program's hot loops are `inc X / dec Y / jnz Y -2` (the
8 * new computer's multiply idiom). Executed naively part 2 burns
9 * 27.7M steps, past the work budget, so at load every such triple is
10 * fused into one op: X += Y; Y = 0 (Y must be positive at the head,
11 * else the original program would never terminate and the fusion
12 * refuses with "loop never terminates"). Fusing swallows two
13 * instruction slots, so any jump landing inside a fused triple is
14 * refused with "jump into fused loop" — that keeps every entry at the
15 * triple head, which is what makes the fusion exact.
16 *
17 * Bounds: at most PROGMAX = 512 instructions with numbers at most 18
18 * digits, and at most STEPMAX = 1000000 interpreted steps (the real
19 * program settles after a few thousand fused steps) — refused beyond
20 * with "program too long", "bad instruction", or "program exceeds the
21 * step budget".
22 *
23 * Part 1 starts all registers at 0; part 2 initializes c to 1 (the
24 * ignition key).
25 */
26
27enum { PROGMAX = 512 };
28
29enum { STEPMAX = 1000000 };
30
31enum {
32    OP_NOP,
33    OP_CPY,
34    OP_INC,
35    OP_DEC,
36    OP_JNZ,
37    OP_ADD /* fused: reg[xr] += reg[yr]; reg[yr] = 0 */
38};
39
40struct ins {
41    uint8_t op;
42    uint8_t xk;  /* 0 = register, 1 = literal (nop/dec/inc/cpy src) */
43    uint8_t xr;  /* x register */
44    uint8_t yr;  /* cpy target / fused zeroed register */
45    int64_t xv;  /* x literal */
46    int32_t off; /* jnz offset */
47};
48
49static struct ins prog[PROGMAX];
50static uint8_t swallowed[PROGMAX];
51static int nins;
52
53/* Next space/newline-free token of the line ending at end. Tokens fit
54 * the 24-byte scratch buffer.
55 */
56static int tok(const uint8_t *s, size_t *i, size_t end, uint8_t *out,
57               size_t *olen) {
58    size_t b;
59
60    while (*i < end && s[*i] == ' ') {
61        (*i)++;
62    }
63    if (*i >= end) {
64        return 0;
65    }
66    b = *i;
67    while (*i < end && s[*i] != ' ') {
68        (*i)++;
69    }
70    aoc_assert(*i - b < 24, "bad instruction");
71    *olen = *i - b;
72    memcpy(out, s + b, *olen);
73    out[*olen] = 0;
74    return 1;
75}
76
77static int is_reg(const uint8_t *t, size_t n, uint8_t *r) {
78    if (n != 1 || t[0] < 'a' || t[0] > 'd') {
79        return 0;
80    }
81    *r = (uint8_t)(t[0] - 'a');
82    return 1;
83}
84
85static void num(const uint8_t *t, size_t n, uint8_t *kind, uint8_t *r,
86                int64_t *v) {
87    size_t k = 0;
88    int neg = 0;
89    int64_t x = 0;
90    int nd = 0;
91
92    if (n > 0 && t[0] == '-') {
93        neg = 1;
94        k = 1;
95    }
96    for (; k < n; k++) {
97        aoc_assert(t[k] >= '0' && t[k] <= '9', "bad instruction");
98        nd++;
99        aoc_assert(nd <= 18, "bad instruction");
100        x = x * 10 + (t[k] - '0');
101    }
102    aoc_assert(nd > 0, "bad instruction");
103    *kind = 1;
104    *r = 0;
105    *v = neg ? -x : x;
106}
107
108static inline __attribute__((always_inline)) size_t
109find_instruction_end(slice input, size_t eol) {
110    while (eol < input.l && input.p[eol] != '\n') {
111        eol++;
112    }
113
114    return eol;
115}
116
117static void load(slice input) {
118    size_t i = 0;
119    uint8_t w[24];
120    size_t wl;
121
122    nins = 0;
123    memset(swallowed, 0, sizeof swallowed);
124    aoc_assert(input.l <= 65536, "input too long");
125    while (i < input.l) {
126        size_t eol = i;
127        struct ins in;
128
129        eol = find_instruction_end(input, eol);
130        if (eol > i && input.p[eol - 1] == '\r') {
131            eol--;
132        }
133        if (eol == i) {
134            i++;
135            continue;
136        }
137        memset(&in, 0, sizeof in);
138        aoc_assert(tok(input.p, &i, eol, w, &wl), "bad instruction");
139        if (wl == 3 && memcmp(w, "cpy", 3) == 0) {
140            in.op = OP_CPY;
141        } else if (wl == 3 && memcmp(w, "inc", 3) == 0) {
142            in.op = OP_INC;
143        } else if (wl == 3 && memcmp(w, "dec", 3) == 0) {
144            in.op = OP_DEC;
145        } else if (wl == 3 && memcmp(w, "jnz", 3) == 0) {
146            in.op = OP_JNZ;
147        } else {
148            aoc_assert(0, "bad instruction");
149        }
150        aoc_assert(tok(input.p, &i, eol, w, &wl), "bad instruction");
151        if (is_reg(w, wl, &in.xr)) {
152            in.xk = 0;
153        } else {
154            num(w, wl, &in.xk, &in.xr, &in.xv);
155        }
156        if (in.op == OP_JNZ) {
157            uint8_t k, r;
158            int64_t v;
159            aoc_assert(tok(input.p, &i, eol, w, &wl), "bad instruction");
160            num(w, wl, &k, &r, &v);
161            in.off = (int32_t)v;
162            aoc_assert(v == (int64_t)in.off, "bad instruction");
163        } else if (in.op == OP_CPY) {
164            aoc_assert(tok(input.p, &i, eol, w, &wl), "bad instruction");
165            aoc_assert(is_reg(w, wl, &in.yr), "bad instruction");
166        } else {
167            aoc_assert(in.xk == 0, "bad instruction");
168        }
169        aoc_assert(!tok(input.p, &i, eol, w, &wl), "bad instruction");
170        aoc_assert(nins < PROGMAX, "program too long");
171        prog[nins++] = in;
172        i = eol;
173        if (i < input.l) {
174            i++;
175        }
176    }
177    aoc_assert(nins > 0, "empty program");
178}
179
180/* Fuse `inc X / dec Y / jnz Y -2` (either body order) into one op at
181 * the head, then refuse any jump into the swallowed slots.
182 */
183static void fuse(void) {
184    int i;
185    int j;
186
187    for (i = 2; i < nins; i++) {
188        struct ins *p, *q;
189        uint8_t x, y;
190
191        if (prog[i].op != OP_JNZ || prog[i].xk != 0 || prog[i].off != -2) {
192            continue;
193        }
194        p = &prog[i - 2];
195        q = &prog[i - 1];
196        if (p->op == OP_INC && q->op == OP_DEC) {
197            x = p->xr;
198            y = q->xr;
199        } else if (p->op == OP_DEC && q->op == OP_INC) {
200            x = q->xr;
201            y = p->xr;
202        } else {
203            continue;
204        }
205        /* Fuse only the multiply idiom: the jnz must test the
206         * decremented register, and the two registers must differ.
207         * Anything else stays naive and burns the step budget only
208         * if it is the hot path.
209         */
210        if (prog[i].xr != y || x == y) {
211            continue;
212        }
213        p->op = OP_ADD;
214        p->xk = 0;
215        p->xr = x;
216        p->yr = y;
217        q->op = OP_NOP;
218        prog[i].op = OP_NOP;
219        swallowed[i - 1] = 1;
220        swallowed[i] = 1;
221    }
222    for (j = 0; j < nins; j++) {
223        int64_t t;
224        if (prog[j].op != OP_JNZ) {
225            continue;
226        }
227        t = (int64_t)j + prog[j].off;
228        if (t >= 0 && t < nins) {
229            aoc_assert(!swallowed[t], "jump into fused loop");
230        }
231    }
232}
233
234static int64_t run(slice input, int64_t c0) {
235    int64_t reg[4];
236    int64_t steps = 0;
237    int64_t pc = 0;
238
239    load(input);
240    fuse();
241    memset(reg, 0, sizeof reg);
242    reg[2] = c0;
243    while (pc >= 0 && pc < nins) {
244        struct ins *in = &prog[pc];
245        steps++;
246        aoc_assert(steps <= STEPMAX, "program exceeds the step budget");
247        switch (in->op) {
248        case OP_CPY:
249            reg[in->yr] = in->xk ? in->xv : reg[in->xr];
250            pc++;
251            break;
252        case OP_INC:
253            aoc_assert(reg[in->xr] < INT64_MAX, "register overflow");
254            reg[in->xr]++;
255            pc++;
256            break;
257        case OP_DEC:
258            aoc_assert(reg[in->xr] > INT64_MIN, "register overflow");
259            reg[in->xr]--;
260            pc++;
261            break;
262        case OP_JNZ:
263            pc += (in->xk ? in->xv : reg[in->xr]) != 0 ? in->off : 1;
264            break;
265        case OP_ADD:
266            aoc_assert(reg[in->yr] > 0, "loop never terminates");
267            aoc_assert(reg[in->xr] <= INT64_MAX - reg[in->yr],
268                       "register overflow");
269            reg[in->xr] += reg[in->yr];
270            reg[in->yr] = 0;
271            pc++;
272            break;
273        default:
274            pc++;
275            break;
276        }
277    }
278    return reg[0];
279}
280
281slice part1(slice input) {
282    return slice_from_i64(run(input, 0));
283}
284
285slice part2(slice input) {
286    return slice_from_i64(run(input, 1));
287}
288
289const struct aoc_method aoc_methods[] = {
290    {0, 0},
291};

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

Four registers and four instructions make a small interpreter a good first move. Keep an instruction pointer, implement each operation literally, and check the example's final a = 42. The jump offset is relative to the jump instruction itself: a taken jump of 2 skips one instruction. Applying an ordinary increment as well would shift every taken jump by one and quietly change the program.

Twenty-three instructions in the local program: surely the train will start soon. Backward jumps make that a poor estimate. Literal execution takes 954,395 instructions for part 1 and 27,683,406 for part 2. A fast one-off interpreter might happily finish both, so we need not pretend simulation is hopeless. But the large difference deserves a look, especially under this repository's work budget. Which tiny loop keeps asking for our time?

Trace inc a, dec b, jnz b -2 with b = 5. Five trips around the loop later, a has grown by five and b is zero. We have watched the machine perform addition one unit at a time. Once we see that, the repeated instructions lose their mystery: replace the whole loop by a = a + b and b = 0. The next instruction receives exactly the state it would have received after all that counting.

Now step back one loop. Save the old a in c, add b into a, copy c into b: the pair changes from (a, b) to (a + b, a). Fibonacci numbers! Part 2's innocent ignition-key change, c = 1, selects a setup branch that increases the outer count from 26 to 33. Seven more additions of growing numbers account for millions more unit increments. A final nested loop adds 19 × 14. What looked like a stubborn little program now has a short mathematical description.

There are two useful stopping points for a solver. Once the recurrence is understood, evaluate it directly and account for the final product. Or keep the interpreter and collapse the addition loops, which retains support for other programs. This implementation chooses the latter. Measured with its replacement slots still visited, the local runs need only 302 and 354 interpreted steps. That reduction comes from recognizing what a repeated block computes.

The replacement needs conditions. The incremented and decremented registers must differ, the jump must test the decremented register, and its starting value must be positive. No other jump may enter the middle of the replaced triple. The implementation validates those conditions and refuses unsafe entries rather than guessing. It accepts at most 512 instructions, 18-digit integer literals, signed 32-bit literal jump offsets, and one million interpreted steps; register arithmetic is checked for signed 64-bit overflow. Input text is capped at 65,536 characters. Programs outside those bounds are refused explicitly.

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.