2025 / Day 11

Reactor

Read the original puzzle on adventofcode.com ↗

The solution

C11

solution.c

1#include "aoc.h"
2
3/* The local input is 9710 bytes, 586 lines, longest line 96. The input contains
4 * 587 device names, 1695 directed wires and at most 23 outputs from one device.
5 * NODES=1024 and EDGES=16384 cover that graph. Only vertices on a start-to-out
6 * route matter; out is terminal. A relevant cycle is refused explicitly. A
7 * topological pass finds reachable visit masks, then a reverse pass counts only
8 * suffixes that complete the required dac/fft visits. This avoids overflowing
9 * on exponentially many paths that would never qualify. Duplicate wires count
10 * once and qualified path counts must fit int64. */
11
12static slice line(slice s, size_t *p) {
13    size_t b = *p;
14    while (*p < s.l && s.p[*p] != '\n') {
15        (*p)++;
16    }
17    size_t e = *p;
18    if (*p < s.l) {
19        (*p)++;
20    }
21    if (e > b && s.p[e - 1] == '\r') {
22        e--;
23    }
24    return (slice){s.p + b, e - b};
25}
26
27static void literal(slice s, size_t *p, const char *t) {
28    size_t n = strlen(t);
29    aoc_assert(*p <= s.l && n <= s.l - *p && memcmp(s.p + *p, t, n) == 0,
30               "bad syntax");
31    *p += n;
32}
33
34static int64_t checked_add(int64_t a, int64_t b) {
35    aoc_assert((b >= 0 && a <= INT64_MAX - b) || (b < 0 && a >= INT64_MIN - b),
36               "answer arithmetic overflow");
37    return a + b;
38}
39
40enum { NODES = 1024, EDGES = 16384, NAMES = 26 * 26 * 26 };
41
42static int32_t names[NAMES], head[NODES], reverse[NODES], to[EDGES],
43    from[EDGES], next[EDGES], back[EDGES], indegree[NODES], queue[NODES];
44static uint8_t defined[NODES], seen[NODES][NODES / 8], forward[NODES],
45    behind[NODES], masks[NODES], key[NODES];
46static int64_t ways[NODES][4];
47static int32_t count, edges;
48
49static int32_t name(slice t, size_t *p) {
50    aoc_assert(t.l - *p >= 3, "device name must have three lowercase letters");
51    int32_t v = 0;
52    for (int32_t k = 0; k < 3; k++) {
53        uint8_t c = t.p[(*p)++];
54        aoc_assert(c >= 'a' && c <= 'z',
55                   "device name must have three lowercase letters");
56        v = v * 26 + c - 'a';
57    }
58    return v;
59}
60
61static int32_t intern(int32_t v) {
62    if (names[v] < 0) {
63        aoc_assert(count < NODES, "more than 1024 devices");
64        names[v] = count++;
65    }
66    return names[v];
67}
68
69static int32_t id(const char *s) {
70    return names[(s[0] - 'a') * 26 * 26 + (s[1] - 'a') * 26 + s[2] - 'a'];
71}
72
73static inline __attribute__((always_inline)) size_t
74read_device_outputs(slice t, size_t q, int32_t a) {
75    while (q < t.l) {
76        literal(t, &q, " ");
77        int32_t b = intern(name(t, &q));
78        if (seen[a][b / 8] & (1u << (b % 8))) {
79            continue;
80        }
81        seen[a][b / 8] |= (uint8_t)(1u << (b % 8));
82        aoc_assert(edges < EDGES, "more than 16384 device wires");
83        to[edges] = b;
84        from[edges] = a;
85        next[edges] = head[a];
86        head[a] = edges;
87        back[edges] = reverse[b];
88        reverse[b] = edges++;
89    }
90
91    return q;
92}
93
94static void parse(slice s) {
95    count = 0;
96    edges = 0;
97    memset(names, 255, sizeof(names));
98    memset(head, 255, sizeof(head));
99    memset(reverse, 255, sizeof(reverse));
100    memset(defined, 0, sizeof(defined));
101    memset(seen, 0, sizeof(seen));
102    size_t p = 0;
103    while (p < s.l) {
104        slice t = line(s, &p);
105        size_t q = 0;
106        int32_t a = intern(name(t, &q));
107        aoc_assert(!defined[a], "device defined more than once");
108        defined[a] = 1;
109        literal(t, &q, ":");
110        q = read_device_outputs(t, q, a);
111    }
112}
113
114static inline __attribute__((always_inline)) size_t
115visit_forward_devices(size_t t, int32_t a) {
116    for (int32_t e = head[a]; e >= 0; e = next[e]) {
117        int32_t b = to[e];
118        if (!forward[b]) {
119            forward[b] = 1;
120            queue[t++] = b;
121        }
122    }
123
124    return t;
125}
126
127static inline __attribute__((always_inline)) size_t
128visit_reverse_devices(int32_t out, size_t t, int32_t a) {
129    for (int32_t e = reverse[a]; e >= 0; e = back[e]) {
130        int32_t b = from[e];
131        if (b != out && !behind[b]) {
132            behind[b] = 1;
133            queue[t++] = b;
134        }
135    }
136
137    return t;
138}
139
140static inline __attribute__((always_inline)) void
141count_relevant_indegrees(int32_t a) {
142    for (int32_t e = head[a]; e >= 0; e = next[e]) {
143        if (behind[to[e]]) {
144            indegree[to[e]]++;
145        }
146    }
147}
148
149static inline __attribute__((always_inline)) void
150propagate_visit_masks(int32_t a, int32_t b) {
151    for (int32_t m = 0; m < 4; m++) {
152        if (masks[a] & (1u << m)) {
153            masks[b] |= (uint8_t)(1u << (m | key[b]));
154        }
155    }
156}
157
158static inline __attribute__((always_inline)) size_t
159visit_device_successors(size_t t, int32_t a) {
160    for (int32_t e = head[a]; e >= 0; e = next[e]) {
161        int32_t b = to[e];
162        if (!behind[b]) {
163            continue;
164        }
165        propagate_visit_masks(a, b);
166        if (!--indegree[b]) {
167            queue[t++] = b;
168        }
169    }
170
171    return t;
172}
173
174static inline __attribute__((always_inline)) void
175add_successor_paths(int32_t a, int32_t m) {
176    for (int32_t e = head[a]; e >= 0; e = next[e]) {
177        int32_t b = to[e];
178        if (behind[b]) {
179            ways[a][m] = checked_add(ways[a][m], ways[b][m | key[b]]);
180        }
181    }
182}
183
184static inline __attribute__((always_inline)) void
185count_device_paths(int32_t part, int32_t out, int32_t a) {
186    for (int32_t m = 0; m < 4; m++) {
187        if (!(masks[a] & (1u << m))) {
188            continue;
189        }
190        if (a == out) {
191            ways[a][m] = part == 1 || m == 3;
192            continue;
193        }
194        add_successor_paths(a, m);
195    }
196}
197
198/* Successor counts are ready in reverse topological order. Advancing to
199 * the preceding device is a tail call, independent of graph depth. */
200static int count_ordered_paths(int32_t part, int32_t out, size_t remaining) {
201    if (!remaining) {
202        return 0;
203    }
204    count_device_paths(part, out, queue[remaining - 1]);
205    return count_ordered_paths(part, out, remaining - 1);
206}
207
208static slice solve(slice s, int32_t part) {
209    parse(s);
210    int32_t start = id(part == 1 ? "you" : "svr"), out = id("out"),
211            dac = id("dac"), fft = id("fft");
212    aoc_assert(start >= 0 && out >= 0, "missing start or out device");
213    aoc_assert(part == 1 || (dac >= 0 && fft >= 0),
214               "missing dac or fft device");
215    memset(forward, 0, sizeof(forward));
216    memset(behind, 0, sizeof(behind));
217    size_t h = 0, t = 0;
218    queue[t++] = start;
219    forward[start] = 1;
220    while (h < t) {
221        int32_t a = queue[h++];
222        if (a == out) {
223            continue;
224        }
225        t = visit_forward_devices(t, a);
226    }
227    h = t = 0;
228    queue[t++] = out;
229    behind[out] = 1;
230    while (h < t) {
231        int32_t a = queue[h++];
232        t = visit_reverse_devices(out, t, a);
233    }
234    if (!forward[out]) {
235        return slice_from_i64(0);
236    }
237    memset(indegree, 0, sizeof(indegree));
238    memset(key, 0, sizeof(key));
239    memset(masks, 0, sizeof(masks));
240    memset(ways, 0, sizeof(ways));
241    int32_t relevant = 0;
242    for (int32_t a = 0; a < count; a++) {
243        if (!forward[a] || !behind[a]) {
244            continue;
245        }
246        relevant++;
247        if (part == 2) {
248            key[a] = (uint8_t)((a == dac ? 1 : 0) | (a == fft ? 2 : 0));
249        }
250        if (a == out) {
251            continue;
252        }
253        count_relevant_indegrees(a);
254    }
255    h = t = 0;
256    for (int32_t a = 0; a < count; a++) {
257        if (forward[a] && behind[a] && !indegree[a]) {
258            queue[t++] = a;
259        }
260    }
261    masks[start] = (uint8_t)(1u << key[start]);
262    while (h < t) {
263        int32_t a = queue[h++];
264        if (a == out) {
265            continue;
266        }
267        t = visit_device_successors(t, a);
268    }
269    aoc_assert((int32_t)t == relevant,
270               "relevant device graph contains a cycle");
271    count_ordered_paths(part, out, t);
272    return slice_from_i64(ways[start][key[start]]);
273}
274
275slice part1(slice s) {
276    return solve(s, 1);
277}
278
279slice part2(slice s) {
280    return solve(s, 2);
281}
282
283const struct aoc_method aoc_methods[] = {{0, 0}};

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 reactor's cables form a directed graph: a device sends data through its listed outputs, and we cannot follow a wire backward. The local rack has 587 device names and 1,695 wires, with at most 23 outputs from one device. Those are small graph dimensions. The question's potentially large quantity is the number of routes through the graph, which can be much greater than the number of devices.

Part one begins at you and ends at out. First inspect what is actually relevant: 130 local devices and 264 wires lie on a route between those endpoints. There are only 566 completed routes, so directly enumerating this part is feasible. It would be reasonable to start with a recursive traversal and count an arrival at out as one completed path.

However, a global visited set would be the wrong kind of shortcut. If two different prefixes arrive at the same device, their completed paths remain different. We should share the computation of the device's possible suffixes, not erase one of the prefixes. In an acyclic graph, define ways(out) = 1 and ways(v) as the sum of ways(w) over its outputs. Memoizing that value, or evaluating it in reverse topological order, counts all paths without listing them. The local graph has no relevant cycle, so this recurrence is well founded.

Part two starts at svr and requires both dac and fft somewhere along each route. The entire local graph is now relevant. It contains about 166 quadrillion server-to-output routes, of which about 332 trillion qualify. At a million completed paths per second, enumerating even the qualifying ones would take more than ten years. Filtering completed routes afterward is not going to be a quick debugging session.

The first adjustment is to identify what history matters. At a given device, have we visited neither required device, dac only, fft only, or both? Those four possibilities are enough. We do not need the full prefix, its length, or the order of all earlier devices. Attach a two-bit visit mask to the current device, set the appropriate bit on arrival at dac or fft, and count a route at out only when both bits are set.

Now memoize (device, visit mask). If different prefixes reach the same pair, their remaining opportunities are identical. There are at most 4 × 587 = 2,348 such states locally, and at most four contributions per directed wire in one counting pass. Only 1,313 device/mask combinations are actually reachable. This is the earned reduction: the enormous collection of journeys contains very little distinct information about what can happen next.

There is also a neat alternative once acyclicity is established. Count paths from svr to fft, fft to dac, and dac to out, then multiply the three counts; add the analogous product for the opposite order. A DAG prevents segment choices from revisiting an earlier vertex, since that would form a cycle. Locally fft can reach dac but dac cannot reach fft, so only the first order contributes. The mask formulation handles the same requirement without choosing an order in advance and extends naturally to more required visits.

The implementation first marks devices reachable from the selected start and devices that can reach out, treating out as terminal. Their intersection removes irrelevant branches. It then computes a topological order while propagating which visit masks are reachable. Finally it works backward, counting only suffixes that will satisfy the required visits. This avoids accumulating huge numerical totals for doomed paths just to discard them later: reachability needs flags, while qualified suffixes need counts.

Up to 1,024 devices and 16,384 distinct directed wires are supported; repeated wire entries count once. A cycle on a start-to-output route is explicitly refused, and qualifying path counts must fit signed 64-bit integers. The story's graph wording alone is not a license to assume all supplied graphs are acyclic, so that check matters. Once the dependency order is established, the reactor's intimidating cable tangle becomes a small table of reusable future questions.

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.