2015 / Day 07

Some Assembly Required

Read the original puzzle on adventofcode.com ↗

The solution

C11

solution.c

1#include "aoc.h"
2
3#include <stdlib.h>
4#include <string.h>
5
6/* 2015 day 7. Circuit of 16-bit wires. */
7
8enum { MAXINSN = 4096 };
9
10enum { MAXWIRE = 4096 };
11
12enum { NAMELEN = 16 };
13
14static int g_insn_op[MAXINSN];
15static int g_insn_lt[MAXINSN];
16static int g_insn_lv[MAXINSN];
17static int g_insn_lw[MAXINSN];
18static int g_insn_rt[MAXINSN];
19static int g_insn_rv[MAXINSN];
20static int g_insn_rw[MAXINSN];
21static int g_insn_for_wire[MAXWIRE];
22static int g_ninsn = 0;
23
24static char g_wire_name[MAXWIRE][NAMELEN + 1];
25static int g_nwire = 0;
26
27static uint8_t g_memoed[MAXWIRE];
28static int g_memoval[MAXWIRE];
29static int g_override = -1;
30static int g_bwire = -1;
31static int g_awire = -1;
32
33static int is_lower(uint8_t c) {
34    return c >= 'a' && c <= 'z';
35}
36
37static int is_digit(uint8_t c) {
38    return c >= '0' && c <= '9';
39}
40
41static int is_ws(uint8_t c) {
42    return c == ' ' || c == '\t' || c == '\r' || c == '\n';
43}
44
45static void skip_ws(slice in, size_t *i) {
46    while (*i < in.l && is_ws(in.p[*i])) {
47        (*i)++;
48    }
49}
50
51static int wire_id(const uint8_t *p, size_t n) {
52    int w;
53    for (w = 0; w < g_nwire; w++) {
54        if (strlen(g_wire_name[w]) == n && memcmp(g_wire_name[w], p, n) == 0) {
55            return w;
56        }
57    }
58    aoc_assert(g_nwire < MAXWIRE, "too many wires");
59    aoc_assert(n > 0 && n <= (size_t)NAMELEN, "wire name bad");
60    memcpy(g_wire_name[g_nwire], p, n);
61    g_wire_name[g_nwire][n] = 0;
62    return g_nwire++;
63}
64
65static int parse_uint_const(slice in, size_t *i) {
66    int v = 0;
67    int nd = 0;
68    skip_ws(in, i);
69    if (*i >= in.l || !is_digit(in.p[*i])) {
70        aoc_assert(0, "bad operand");
71    }
72    while (*i < in.l && is_digit(in.p[*i])) {
73        v = v * 10 + (int)(in.p[*i] - '0');
74        aoc_assert(v <= 65535, "bad constant");
75        (*i)++;
76        nd++;
77    }
78    aoc_assert(nd > 0, "bad operand");
79    return v;
80}
81
82/* parse an operand, write 0=const 1=wire */
83static void parse_operand(slice in, size_t *i, int *type, int *val, int *wire) {
84    skip_ws(in, i);
85    aoc_assert(*i < in.l, "bad expression");
86    if (is_digit(in.p[*i])) {
87        *type = 0;
88        *val = parse_uint_const(in, i);
89        *wire = -1;
90    } else if (is_lower(in.p[*i])) {
91        size_t s = *i;
92        while (*i < in.l && is_lower(in.p[*i])) {
93            (*i)++;
94        }
95        *type = 1;
96        *val = 0;
97        *wire = wire_id(in.p + s, *i - s);
98    } else {
99        aoc_assert(0, "bad operand");
100    }
101}
102
103static int find_wire(const char *name) {
104    int w;
105    for (w = 0; w < g_nwire; w++) {
106        if (memcmp(g_wire_name[w], name, strlen(name) + 1) == 0) {
107            return w;
108        }
109    }
110    return -1;
111}
112
113static inline __attribute__((always_inline)) size_t scan_operator(slice input,
114                                                                  size_t i) {
115    while (i < input.l && input.p[i] >= 'A' && input.p[i] <= 'Z') {
116        i++;
117    }
118
119    return i;
120}
121
122static void load(slice input) {
123    size_t i = 0;
124    int w;
125    aoc_assert(input.l <= (1u << 20), "input too large");
126
127    g_ninsn = 0;
128    g_nwire = 0;
129    for (w = 0; w < MAXWIRE; w++) {
130        g_insn_for_wire[w] = -1;
131    }
132
133    skip_ws(input, &i);
134    while (i < input.l) {
135        int op = 0;
136        int lt = 0, lv = 0, lw = -1;
137        int rt = 0, rv = 0, rw = -1;
138        int target = -1;
139
140        /* unary NOT? */
141        if (i + 3 <= input.l && memcmp(input.p + i, "NOT", 3) == 0 &&
142            (i + 3 == input.l || !is_lower(input.p[i + 3]))) {
143            i += 3;
144            parse_operand(input, &i, &lt, &lv, &lw);
145            skip_ws(input, &i);
146            aoc_assert(i + 2 <= input.l && input.p[i] == '-' &&
147                           input.p[i + 1] == '>',
148                       "bad arrow");
149            i += 2;
150            op = 5;
151        } else {
152            parse_operand(input, &i, &lt, &lv, &lw);
153            skip_ws(input, &i);
154            if (i + 2 <= input.l && input.p[i] == '-' &&
155                input.p[i + 1] == '>') {
156                op = 0;
157                i += 2;
158            } else {
159                size_t s = i;
160                i = scan_operator(input, i);
161                aoc_assert(i > s, "bad operator");
162                if (i - s == 3 && memcmp(input.p + s, "AND", 3) == 0) {
163                    op = 1;
164                } else if (i - s == 2 && memcmp(input.p + s, "OR", 2) == 0) {
165                    op = 2;
166                } else if (i - s == 6 &&
167                           memcmp(input.p + s, "LSHIFT", 6) == 0) {
168                    op = 3;
169                } else if (i - s == 6 &&
170                           memcmp(input.p + s, "RSHIFT", 6) == 0) {
171                    op = 4;
172                } else {
173                    aoc_assert(0, "bad operator");
174                }
175                parse_operand(input, &i, &rt, &rv, &rw);
176                skip_ws(input, &i);
177                aoc_assert(i + 2 <= input.l && input.p[i] == '-' &&
178                               input.p[i + 1] == '>',
179                           "bad arrow");
180                i += 2;
181            }
182        }
183
184        /* target wire */
185        int ttype = 0, tval = 0, tw = -1;
186        parse_operand(input, &i, &ttype, &tval, &tw);
187        aoc_assert(ttype == 1, "bad target");
188        target = tw;
189        skip_ws(input, &i);
190
191        aoc_assert(g_ninsn < MAXINSN, "too many instructions");
192        g_insn_op[g_ninsn] = op;
193        g_insn_lt[g_ninsn] = lt;
194        g_insn_lv[g_ninsn] = lv;
195        g_insn_lw[g_ninsn] = lw;
196        g_insn_rt[g_ninsn] = rt;
197        g_insn_rv[g_ninsn] = rv;
198        g_insn_rw[g_ninsn] = rw;
199        aoc_assert(g_insn_for_wire[target] == -1, "duplicate wire source");
200        g_insn_for_wire[target] = g_ninsn;
201        g_ninsn++;
202    }
203
204    aoc_assert(g_ninsn > 0, "empty input");
205
206    g_awire = find_wire("a");
207    g_bwire = find_wire("b");
208    aoc_assert(g_awire >= 0, "no wire a");
209}
210
211static int eval_wire(int idx, int depth) {
212    int itype;
213    uint16_t lval, rval, res;
214    int ins;
215
216    if (g_override >= 0 && idx == g_bwire) {
217        return g_override;
218    }
219    aoc_assert(depth < 128, "circuit too deep");
220    aoc_assert(g_memoed[idx] != 2, "circuit cycle");
221    if (g_memoed[idx] == 1) {
222        return g_memoval[idx];
223    }
224    ins = g_insn_for_wire[idx];
225    aoc_assert(ins >= 0, "wire has no source");
226
227    g_memoed[idx] = 2;
228    /* left */
229    if (g_insn_lt[ins] == 0) {
230        lval = (uint16_t)g_insn_lv[ins];
231    } else {
232        lval = (uint16_t)eval_wire(g_insn_lw[ins], depth + 1);
233    }
234
235    switch (g_insn_op[ins]) {
236    case 0: /* assign */
237        res = lval;
238        break;
239    case 5: /* not */
240        res = (uint16_t)(~lval);
241        break;
242    case 1: /* AND */
243        if (g_insn_rt[ins] == 0) {
244            rval = (uint16_t)g_insn_rv[ins];
245        } else {
246            rval = (uint16_t)eval_wire(g_insn_rw[ins], depth + 1);
247        }
248        res = (uint16_t)(lval & rval);
249        break;
250    case 2: /* OR */
251        if (g_insn_rt[ins] == 0) {
252            rval = (uint16_t)g_insn_rv[ins];
253        } else {
254            rval = (uint16_t)eval_wire(g_insn_rw[ins], depth + 1);
255        }
256        res = (uint16_t)(lval | rval);
257        break;
258    case 3: /* LSHIFT */
259        if (g_insn_rt[ins] == 0) {
260            rval = (uint16_t)g_insn_rv[ins];
261        } else {
262            rval = (uint16_t)eval_wire(g_insn_rw[ins], depth + 1);
263        }
264        aoc_assert(rval <= 15, "bad shift");
265        res = (uint16_t)(lval << rval);
266        break;
267    case 4: /* RSHIFT */
268        if (g_insn_rt[ins] == 0) {
269            rval = (uint16_t)g_insn_rv[ins];
270        } else {
271            rval = (uint16_t)eval_wire(g_insn_rw[ins], depth + 1);
272        }
273        aoc_assert(rval <= 15, "bad shift");
274        res = (uint16_t)(lval >> rval);
275        break;
276    default:
277        aoc_assert(0, "bad opcode");
278    }
279
280    g_memoed[idx] = 1;
281    g_memoval[idx] = (int)res;
282    itype = 0;
283    (void)itype;
284    return g_memoval[idx];
285}
286
287static int solve(slice input, int override) {
288    int a;
289    int w;
290    load(input);
291    g_override = override;
292    for (w = 0; w < g_nwire; w++) {
293        g_memoed[w] = 0;
294    }
295    a = eval_wire(g_awire, 0);
296    return a;
297}
298
299slice part1(slice input) {
300    return slice_from_i64((int64_t)solve(input, -1));
301}
302
303slice part2(slice input) {
304    int a = solve(input, -1);
305    return slice_from_i64((int64_t)solve(input, a));
306}
307
308const struct aoc_method aoc_methods[] = {
309    {0, 0},
310};

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

The first snag can arrive before we evaluate a single gate: an instruction asks for a wire whose value we have not seen yet. Did we miss a line? Probably not. The booklet describes how a circuit is connected, so file order is not execution order. The local input has 339 instructions, each giving one wire a single source and a signal between 0 and 65,535.

We could keep scanning the booklet, filling in whichever wires now have known inputs. With only a few hundred instructions, that is a perfectly respectable way to get started. But notice how specific the question is: what reaches wire a? Try working backward from there. What produces a? Which wires does that gate need? Ask the same question for those wires until we reach constants, then let the answers work their way back up.

This feels almost like asking the circuit to explain itself. There is one catch: two branches of that explanation may ask for the same wire. Rebuilding it every time would repeat all the work feeding it. Once a wire's value is known, write it down and reuse it. That small act is memoization. After parsing, each required gate is evaluated once, and each has at most two input dependencies. We have followed the question's curiosity instead of repeatedly searching the entire booklet for something to do.

Before celebrating, check NOT 123 against the example. The answer is 65,412. If the language gives us a negative number instead, the circuit is not broken; our model forgot that these wires carry exactly sixteen bits. Complement within that width, and retain only the low sixteen bits after a left shift. The story's number bounds are doing real work here.

Part 2 is wonderfully capable of producing an answer that looks suspiciously familiar. Override b, ask for a again—and a cache may confidently hand back yesterday's answer without evaluating anything. The saved values belong to the old circuit. Keep the first answer, clear those values, replace b's source with that answer, and start again. The wiring can be reused; the conclusions drawn from the old inputs must be reconsidered.

The implementation accepts at most 4,096 instructions and wires, names of at most 16 letters, and shifts 0–15. Marking a wire as currently being evaluated detects a dependency cycle. Recursive calls must stay below depth 128; the measured memoized evaluation reaches depth 40 in both parts. That call depth differs from the graph's longest dependency path because some dependencies may already be cached. Missing sources and excessive depth are explicitly refused.

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.