2016 / Day 25

Clock Signal

Read the original puzzle on adventofcode.com ↗

The solution

C11

solution.c

1#include "aoc.h"
2
3/* At most 256 instructions; literal magnitudes <= 1e9, registers stay
4 * inside +/-1e12. Recognize loops at execution time so toggles and jumps
5 * into a loop's interior retain their original semantics. */
6enum { PROGMAX = 256, STEPMAX = 1000000 };
7
8static const int64_t REGCAP = 1000000000000LL;
9
10enum { CPY, INC, DEC, JNZ, TGL, OUT };
11
12struct arg {
13    int8_t reg;
14    int64_t val;
15};
16
17struct ins {
18    uint8_t op;
19    struct arg x, y;
20};
21static struct ins program[PROGMAX], code[PROGMAX];
22static int nins;
23
24static struct arg operand(slice line, size_t *i) {
25    while (*i < line.l && (line.p[*i] == ' ' || line.p[*i] == '\t')) {
26        (*i)++;
27    }
28    size_t start = *i;
29    while (*i < line.l && line.p[*i] != ' ' && line.p[*i] != '\t') {
30        (*i)++;
31    }
32    size_t end = *i;
33    aoc_assert(end > start, "missing operand");
34    struct arg a = {-1, 0};
35    if (end - start == 1 && line.p[start] >= 'a' && line.p[start] <= 'd') {
36        a.reg = (int8_t)(line.p[start] - 'a');
37        return a;
38    }
39    int neg = line.p[start] == '-';
40    if (neg || line.p[start] == '+') {
41        start++;
42    }
43    aoc_assert(start < end, "bad operand");
44    for (; start < end; start++) {
45        uint8_t c = line.p[start];
46        aoc_assert(c >= '0' && c <= '9', "bad operand");
47        aoc_assert(a.val <= (1000000000 - (c - '0')) / 10, "operand too large");
48        a.val = a.val * 10 + (c - '0');
49    }
50    if (neg) {
51        a.val = -a.val;
52    }
53    return a;
54}
55
56static inline __attribute__((always_inline)) size_t
57find_instruction_end(slice in, size_t end) {
58    while (end < in.l && in.p[end] != '\n') {
59        end++;
60    }
61
62    return end;
63}
64
65static inline __attribute__((always_inline)) size_t
66skip_instruction_spaces(size_t len, slice line, size_t p) {
67    while (p < len && (line.p[p] == ' ' || line.p[p] == '\t')) {
68        p++;
69    }
70
71    return p;
72}
73
74static inline __attribute__((always_inline)) size_t scan_opcode(size_t len,
75                                                                slice line,
76                                                                size_t p) {
77    while (p < len && line.p[p] != ' ' && line.p[p] != '\t') {
78        p++;
79    }
80
81    return p;
82}
83
84static inline __attribute__((always_inline)) void
85identify_opcode(slice line, size_t op, const char *names[], int *k_ref) {
86    for ((*k_ref) = 0; (*k_ref) < 6; (*k_ref)++) {
87        if (!memcmp(line.p + op, names[(*k_ref)], 3)) {
88            break;
89        }
90    }
91}
92
93static inline __attribute__((always_inline)) size_t
94skip_operand_spaces(size_t len, slice line, size_t p) {
95    while (p < len && (line.p[p] == ' ' || line.p[p] == '\t')) {
96        p++;
97    }
98
99    return p;
100}
101
102static void load(slice in) {
103    size_t i = 0;
104    nins = 0;
105    aoc_assert(in.l <= 65536, "input too long");
106    while (i < in.l) {
107        size_t end = i;
108        end = find_instruction_end(in, end);
109        size_t len = end - i;
110        if (len && in.p[i + len - 1] == '\r') {
111            len--;
112        }
113        slice line = {in.p + i, len};
114        size_t p = 0;
115        p = skip_instruction_spaces(len, line, p);
116        if (p < len) {
117            size_t op = p;
118            p = scan_opcode(len, line, p);
119            aoc_assert(p - op == 3, "bad instruction");
120            struct ins x = {0};
121            const char *names[] = {"cpy", "inc", "dec", "jnz", "tgl", "out"};
122            int k;
123            identify_opcode(line, op, names, &k);
124            aoc_assert(k < 6, "bad instruction");
125            x.op = (uint8_t)k;
126            x.x = operand(line, &p);
127            x.y.reg = -1;
128            if (k == CPY || k == JNZ) {
129                x.y = operand(line, &p);
130            }
131            p = skip_operand_spaces(len, line, p);
132            aoc_assert(p == len, "bad instruction");
133            aoc_assert(nins < PROGMAX, "program too long");
134            program[nins++] = x;
135        }
136        i = end < in.l ? end + 1 : end;
137    }
138    aoc_assert(nins > 0, "empty program");
139}
140
141static int64_t value(struct arg a, const int64_t r[4]) {
142    return a.reg < 0 ? a.val : r[a.reg];
143}
144
145static int literal(struct arg a, int64_t v) {
146    return a.reg < 0 && a.val == v;
147}
148
149static void add(int64_t *a, int64_t b) {
150    aoc_assert(b >= -REGCAP && b <= REGCAP && *a <= REGCAP - b &&
151                   *a >= -REGCAP - b,
152               "register exceeds cap");
153    *a += b;
154}
155
156/* Only positive, terminating add/multiply idioms, with non-aliased
157 * counters and a source that stays constant throughout the loop. */
158static int optimize(int pc, int64_t r[4]) {
159    struct ins *p = code + pc;
160    /* Exact division idiom: consume pairs from B, increment A, leave
161     * C as 2-remainder. All branch operands and register aliases matter. */
162    if (pc + 7 < nins && p[0].op == CPY && literal(p[0].x, 2) &&
163        p[1].op == JNZ && literal(p[1].y, 2) && p[2].op == JNZ &&
164        literal(p[2].x, 1) && literal(p[2].y, 6) && p[3].op == DEC &&
165        p[4].op == DEC && p[5].op == JNZ && literal(p[5].y, -4) &&
166        p[6].op == INC && p[7].op == JNZ && literal(p[7].x, 1) &&
167        literal(p[7].y, -7)) {
168        int a = p[6].x.reg, b = p[3].x.reg, c = p[4].x.reg;
169        if (a >= 0 && b >= 0 && c >= 0 && a != b && a != c && b != c &&
170            p[0].y.reg == c && p[1].x.reg == b && p[5].x.reg == c &&
171            r[b] >= 0) {
172            add(&r[a], r[b] / 2);
173            r[c] = 2 - r[b] % 2;
174            r[b] = 0;
175            return 8;
176        }
177    }
178    if (pc + 5 < nins && p[0].op == CPY && p[1].op == INC && p[2].op == DEC &&
179        p[3].op == JNZ && p[4].op == DEC && p[5].op == JNZ) {
180        int a = p[1].x.reg, b = p[2].x.reg, c = p[4].x.reg;
181        if (a >= 0 && b >= 0 && c >= 0 && a != b && a != c && b != c &&
182            p[0].y.reg == b && p[3].x.reg == b && literal(p[3].y, -2) &&
183            p[5].x.reg == c && literal(p[5].y, -5) && p[0].x.reg != a &&
184            p[0].x.reg != b && p[0].x.reg != c) {
185            int64_t x = value(p[0].x, r), y = r[c];
186            if (x > 0 && y > 0) {
187                aoc_assert(x <= REGCAP / y, "register exceeds cap");
188                add(&r[a], x * y);
189                r[b] = r[c] = 0;
190                return 6;
191            }
192        }
193    }
194    if (pc + 2 < nins && p[2].op == JNZ && literal(p[2].y, -2)) {
195        struct ins *inc = p, *dec = p + 1;
196        if (inc->op == DEC && dec->op == INC) {
197            inc = p + 1;
198            dec = p;
199        }
200        int a = inc->x.reg, b = dec->x.reg;
201        if (inc->op == INC && dec->op == DEC && a >= 0 && b >= 0 && a != b &&
202            p[2].x.reg == b && r[b] > 0) {
203            add(&r[a], r[b]);
204            r[b] = 0;
205            return 3;
206        }
207    }
208    return 0;
209}
210
211static int64_t execute(int64_t pc, int64_t r[4]) {
212    int skip = optimize((int)pc, r);
213    if (skip) {
214        return pc + skip;
215    }
216    struct ins in = code[pc];
217    int64_t x = value(in.x, r);
218    switch (in.op) {
219    case CPY:
220        if (in.y.reg >= 0) {
221            r[in.y.reg] = x;
222        }
223        break;
224    case INC:
225        if (in.x.reg >= 0) {
226            add(&r[in.x.reg], 1);
227        }
228        break;
229    case DEC:
230        if (in.x.reg >= 0) {
231            add(&r[in.x.reg], -1);
232        }
233        break;
234    case JNZ:
235        if (x) {
236            return pc + value(in.y, r);
237        }
238        break;
239    case TGL: {
240        int64_t q = pc + x;
241        if (q >= 0 && q < nins) {
242            uint8_t op = code[q].op;
243            code[q].op = op == CPY || op == JNZ ? (op == JNZ ? CPY : JNZ)
244                                                : (op == INC ? DEC : INC);
245        }
246        break;
247    }
248    default:
249        aoc_assert(0, "unexpected output instruction");
250    }
251    return pc + 1;
252}
253
254/* A repeated full machine state at an output proves an infinite clock.
255 * Matching a finite prefix does not. With no toggles the program itself
256 * is immutable, so pc, registers and expected bit are the full state. */
257enum { SEEN = 8192, AMAX = 10000, TOTALSTEPS = 2000000 };
258
259struct state {
260    int64_t r[4];
261    int32_t pc;
262    uint8_t bit;
263    int32_t generation;
264};
265static struct state seen[SEEN];
266
267static int repeated(int32_t pc, int64_t r[4], int bit, int a) {
268    uint64_t hash = (uint64_t)pc * 37 + (uint64_t)bit;
269    for (int k = 0; k < 4; k++) {
270        hash = (hash ^ (uint64_t)r[k]) * 0x9e3779b185ebca87ULL;
271    }
272    size_t slot = (size_t)(hash ^ (hash >> 32)) & (SEEN - 1);
273    for (int count = 0; count < SEEN; count++) {
274        struct state *s = seen + slot;
275        if (s->generation != a) {
276            memcpy(s->r, r, sizeof s->r);
277            s->pc = pc;
278            s->bit = (uint8_t)bit;
279            s->generation = a;
280            return 0;
281        }
282        if (s->pc == pc && s->bit == bit && !memcmp(s->r, r, sizeof s->r)) {
283            return 1;
284        }
285        slot = (slot + 1) & (SEEN - 1);
286    }
287    aoc_assert(0, "clock states exceed cap");
288}
289
290static inline __attribute__((always_inline)) int
291test_clock_candidate(int *total_ref, int a, int64_t r[4], int64_t *pc_ref,
292                     int *bit_ref, int *steps_ref, slice *answer_out) {
293    while ((*pc_ref) >= 0 && (*pc_ref) < nins) {
294        aoc_assert(++(*steps_ref) <= STEPMAX && ++(*total_ref) <= TOTALSTEPS,
295                   "clock search exceeds step budget");
296        if (code[(*pc_ref)].op == OUT) {
297            if (value(code[(*pc_ref)].x, r) != (*bit_ref)) {
298                break;
299            }
300            if (repeated((int32_t)(*pc_ref), r, (*bit_ref), a)) {
301                {
302                    *answer_out = slice_from_i64(a);
303                    return 1;
304                };
305            }
306            (*bit_ref) ^= 1;
307            (*pc_ref)++;
308        } else {
309            (*pc_ref) = execute((*pc_ref), r);
310        }
311    }
312
313    return 0;
314}
315
316slice part1(slice in) {
317    load(in);
318    for (int k = 0; k < nins; k++) {
319        aoc_assert(program[k].op != TGL, "clock program must not toggle");
320    }
321    memcpy(code, program, (size_t)nins * sizeof code[0]);
322    int total = 0;
323    for (int a = 1; a <= AMAX; a++) {
324        int64_t r[4] = {a, 0, 0, 0}, pc = 0;
325        int bit = 0, steps = 0;
326        if (a == 1) {
327            memset(seen, 0, sizeof seen);
328        }
329        {
330            slice answer;
331            if (test_clock_candidate(&total, a, r, &pc, &bit, &steps,
332                                     &answer)) {
333                return answer;
334            }
335        }
336    }
337    aoc_assert(0, "no clock seed within cap");
338}
339
340slice part2(slice in) {
341    (void)in;
342    aoc_assert(0, "no part two");
343}
344
345static slice estimate(slice in) {
346    load(in);
347    for (int k = 0; k < nins; k++) {
348        aoc_assert(program[k].op != TGL, "clock program must not toggle");
349    }
350    return slice_from_i64(AMAX);
351}
352
353const struct aoc_method aoc_methods[] = {
354    {"estimate", estimate},
355    {0, 0},
356};

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 made it to the roof with the stars, the antenna, and one last program that refuses to cooperate. Add out to the interpreter and let the machine show us something. Try positive initial values of a in order, watching for 0, 1, 0, 1. Stop a candidate as soon as it emits the wrong value or halts. The local program has thirty instructions and just one output instruction; observing that point gives a much clearer experiment than pages of register traces.

Eventually a candidate keeps alternating. Ten outputs, a hundred—can we stop watching? The word “forever” makes that uncomfortable. A long countdown could fail just after we look away. Instead, record the complete state at every valid output: instruction position, all four registers, and the expected bit. If one repeats, the machine is in precisely the same situation and must repeat the same behavior. Because we witnessed outputs between the repeats, this is a productive cycle. Now we have a reason to stop watching: the clock will continue.

This also explains what must not be merged. Equal output bits alone say almost nothing; even equal registers at different instructions can lead to different futures. The expected phase belongs to the state too. If the program could modify itself, its current code would also matter. This implementation restricts clock programs to those without tgl, making the instruction position and registers a complete description of the machine's future alongside the required phase.

Curiosity offers another route into the same result. The local setup saves a + 11 × 231, or a + 2,541. Watch the next loop consume units in pairs while counting how many pairs it removed. Division by two, written in assembunny. It outputs the leftover bit, repeats with the quotient, and reloads the saved number when the quotient reaches zero. The apparently mysterious signal is that number's binary digits, read from the least significant end over and over.

That makes the desired numbers almost visible: their low-to-high bits must be 0, 1, 0, 1, …, ending with one so the next repetition starts correctly. Written normally, they are 10, 1010, 101010, … in binary: decimal 2, 10, 42, 170, 682, 2,730. Each is four times its predecessor plus two. Find the first above the setup offset and subtract that offset. We have gone from watching a machine and hoping it continues to understanding exactly which inputs make it sing the required rhythm.

The implementation retains an interpreter and searches seeds in order, collapsing exact addition, multiplication, and division-by-two loops. The local first valid candidate repeats an output state on its thirteenth output; a literal reference run reaches that proof in 52,899 instructions. All smaller candidates fail, with no more than seven initially correct outputs each. These measurements support the experiment, while the repeated state supplies the proof. If a smaller candidate merely exhausts its work allowance, it cannot safely be skipped: its status is unresolved, so the solver refuses rather than claiming a later seed is minimal.

Supported programs have at most 256 instructions, literal magnitudes through one billion, registers within ±one trillion, and no toggles. Seeds range from 1 through 10,000. Each candidate may record 8,192 output states and execute one million interpreted steps, with two million steps across the whole search. Input text is capped at 65,536 characters. The estimate method reports the fixed seed cap. Day 25's second star has no computational part two.

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.