2023 / Day 08

Haunted Wasteland

Read the original puzzle on adventofcode.com ↗

The solution

C11

solution.c

1#include "aoc.h"
2
3/* The local input is 13157 bytes, 760 lines, longest line 269. The input has
4 * 758 nodes, 269 directions and six A-ending starts. NODES = 1024, DIRS = 512,
5 * STARTS = 32 and WORK = 2000000 walk transitions bound exact state-cycle
6 * discovery. Keep all Z residues (up to 64 per start), check transient hits,
7 * then combine residues with generalized CRT rather than assuming first hits
8 * are periods. */
9
10static slice line(slice s, size_t *p) {
11    size_t b = *p;
12    while (*p < s.l && s.p[*p] != '\n') {
13        (*p)++;
14    }
15    size_t e = *p;
16    if (*p < s.l) {
17        (*p)++;
18    }
19    if (e > b && s.p[e - 1] == '\r') {
20        e--;
21    }
22    return (slice){s.p + b, e - b};
23}
24
25static void literal(slice s, size_t *p, const char *t) {
26    size_t n = strlen(t);
27    aoc_assert(*p <= s.l && n <= s.l - *p && memcmp(s.p + *p, t, n) == 0,
28               "bad syntax");
29    *p += n;
30}
31
32enum {
33    NODES = 1024,
34    DIRS = 512,
35    STARTS = 32,
36    HITS = 64,
37    COMBINATIONS = 256,
38    WORK = 2000000,
39    CODES = 36 * 36 * 36,
40    STATES = NODES * DIRS
41};
42
43static int32_t lookup[CODES], edge[NODES][2], code[NODES], seen[STATES];
44static uint8_t defined[NODES], dirs[DIRS];
45static int32_t n, nd, work;
46
47typedef struct {
48    int32_t mu, period, count, hit[HITS];
49} Cycle;
50
51static int32_t digit(uint8_t c) {
52    if (c >= 'A' && c <= 'Z') {
53        return c - 'A' + 10;
54    }
55    aoc_assert(c >= '0' && c <= '9', "bad node name");
56    return c - '0';
57}
58
59static int32_t name(slice s, size_t *p) {
60    aoc_assert(*p + 3 <= s.l, "short node name");
61    int32_t v = 0;
62    for (int32_t i = 0; i < 3; i++) {
63        v = v * 36 + digit(s.p[(*p)++]);
64    }
65    return v;
66}
67
68static int32_t node(int32_t v) {
69    if (!lookup[v]) {
70        aoc_assert(n < NODES, "network exceeds 1024 nodes");
71        lookup[v] = ++n;
72        code[n - 1] = v;
73    }
74    return lookup[v] - 1;
75}
76
77static int32_t step(int32_t u, int32_t t) {
78    aoc_assert(++work <= WORK, "network walk exceeds 2000000 transitions");
79    return edge[u][dirs[t % nd]];
80}
81
82static Cycle cycle(int32_t u) {
83    Cycle c = {0};
84    memset(seen, 0, n * nd * sizeof *seen);
85    int32_t t = 0;
86    while (!seen[u * nd + t % nd]) {
87        seen[u * nd + t % nd] = t + 1;
88        if (code[u] % 36 == 35) {
89            aoc_assert(c.count < HITS,
90                       "walk has more than 64 Z hits before repeating");
91            c.hit[c.count++] = t;
92        }
93        u = step(u, t++);
94    }
95    c.mu = seen[u * nd + t % nd] - 1;
96    c.period = t - c.mu;
97    return c;
98}
99
100static int32_t hits(Cycle *c, int32_t t) {
101    for (int32_t i = 0; i < c->count; i++) {
102        if (t < c->mu) {
103            if (t == c->hit[i]) {
104                return 1;
105            }
106        } else if (c->hit[i] >= c->mu && (t - c->hit[i]) % c->period == 0) {
107            return 1;
108        }
109    }
110    return 0;
111}
112
113static int64_t gcd64(int64_t a, int64_t b) {
114    while (b) {
115        int64_t t = a % b;
116        a = b;
117        b = t;
118    }
119    return a;
120}
121
122static int64_t inverse(int64_t a, int64_t m) {
123    int64_t b = m, x = 1, y = 0;
124    while (b) {
125        int64_t q = a / b, t = a - q * b;
126        a = b;
127        b = t;
128        t = x - q * y;
129        x = y;
130        y = t;
131    }
132    return (x % m + m) % m;
133}
134
135static inline __attribute__((always_inline)) int32_t
136all_ghosts_at_goal(Cycle cycles[STARTS], int32_t nc, int32_t t, int32_t all) {
137    for (int32_t i = 0; i < nc; i++) {
138        if (!hits(&cycles[i], t)) {
139            all = 0;
140            break;
141        }
142    }
143
144    return all;
145}
146
147static inline __attribute__((always_inline)) int32_t find_existing_residue(
148    int64_t next[COMBINATIONS], int32_t nn, int64_t v, int32_t z) {
149    while (z < nn && next[z] != v) {
150        z++;
151    }
152
153    return z;
154}
155
156static inline __attribute__((always_inline)) int32_t combine_cycle_hits(
157    Cycle cycles[STARTS], int64_t values[COMBINATIONS],
158    int64_t next[COMBINATIONS], int64_t mod, int32_t c, int64_t g, int64_t m,
159    int64_t newmod, int64_t inv, int32_t nn, int32_t i) {
160    for (int32_t j = 0; j < cycles[c].count; j++) {
161        int32_t h = cycles[c].hit[j];
162        if (h < cycles[c].mu) {
163            continue;
164        }
165        int64_t delta = h - values[i];
166        if (delta % g) {
167            continue;
168        }
169        int64_t k = m == 1 ? 0 : (((delta / g) % m + m) % m * inv) % m;
170        int64_t v = (values[i] + mod * k) % newmod;
171        int32_t z = 0;
172        z = find_existing_residue(next, nn, v, z);
173        if (z == nn) {
174            aoc_assert(nn < COMBINATIONS,
175                       "ghost CRT exceeds 256 residue combinations");
176            next[nn++] = v;
177        }
178    }
179
180    return nn;
181}
182
183static inline __attribute__((always_inline)) int32_t combine_cycle_residues(
184    Cycle cycles[STARTS], int64_t values[COMBINATIONS],
185    int64_t next[COMBINATIONS], int64_t mod, int32_t count, int32_t c,
186    int64_t g, int64_t m, int64_t newmod, int64_t inv, int32_t nn) {
187    for (int32_t i = 0; i < count; i++) {
188        nn = combine_cycle_hits(cycles, values, next, mod, c, g, m, newmod, inv,
189                                nn, i);
190    }
191
192    return nn;
193}
194
195static slice solve(slice s, int32_t part) {
196    memset(lookup, 0, sizeof lookup);
197    memset(defined, 0, sizeof defined);
198    n = nd = work = 0;
199    size_t p = 0;
200    slice l = line(s, &p);
201    aoc_assert(l.l && l.l <= DIRS, "directions exceed 512 or are empty");
202    nd = l.l;
203    for (int32_t i = 0; i < nd; i++) {
204        aoc_assert(l.p[i] == 'L' || l.p[i] == 'R', "bad direction");
205        dirs[i] = l.p[i] == 'R';
206    }
207    while (p < s.l) {
208        l = line(s, &p);
209        if (!l.l) {
210            continue;
211        }
212        size_t q = 0;
213        int32_t a = node(name(l, &q));
214        literal(l, &q, " = (");
215        int32_t b = node(name(l, &q));
216        literal(l, &q, ", ");
217        int32_t c = node(name(l, &q));
218        literal(l, &q, ")");
219        aoc_assert(q == l.l && !defined[a],
220                   "duplicate node or trailing network data");
221        defined[a] = 1;
222        edge[a][0] = b;
223        edge[a][1] = c;
224    }
225    for (int32_t i = 0; i < n; i++) {
226        aoc_assert(defined[i], "undefined network node");
227    }
228    if (part == 1) {
229        int32_t aaa = 10 * (36 * 36 + 36 + 1), zzz = 35 * (36 * 36 + 36 + 1);
230        aoc_assert(lookup[aaa] && lookup[zzz], "network needs AAA and ZZZ");
231        int32_t u = lookup[aaa] - 1, t = 0;
232        memset(seen, 0, n * nd * sizeof *seen);
233        while (code[u] != zzz) {
234            aoc_assert(!seen[u * nd + t % nd], "ZZZ is unreachable");
235            seen[u * nd + t % nd] = 1;
236            u = step(u, t++);
237        }
238        return slice_from_i64(t);
239    }
240    Cycle cycles[STARTS];
241    int32_t nc = 0, mu = 0;
242    for (int32_t i = 0; i < n; i++) {
243        if (code[i] % 36 == 10) {
244            aoc_assert(nc < STARTS, "more than 32 ghost starts");
245            cycles[nc] = cycle(i);
246            if (cycles[nc].mu > mu) {
247                mu = cycles[nc].mu;
248            }
249            nc++;
250        }
251    }
252    aoc_assert(nc, "no A-ending start nodes");
253    for (int32_t t = 0; t < mu; t++) {
254        int32_t all = 1;
255        all = all_ghosts_at_goal(cycles, nc, t, all);
256        if (all) {
257            return slice_from_i64(t);
258        }
259    }
260    int64_t values[COMBINATIONS] = {0}, next[COMBINATIONS], mod = 1;
261    int32_t count = 1;
262    for (int32_t c = 0; c < nc; c++) {
263        int64_t period = cycles[c].period, g = gcd64(mod, period),
264                m = period / g;
265        aoc_assert(mod <= INT64_MAX / m,
266                   "ghost cycle lcm exceeds signed 64 bits");
267        int64_t newmod = mod * m, inv = m == 1 ? 0 : inverse((mod / g) % m, m);
268        int32_t nn = 0;
269        nn = combine_cycle_residues(cycles, values, next, mod, count, c, g, m,
270                                    newmod, inv, nn);
271        aoc_assert(nn, "ghost walks never reach Z simultaneously");
272        count = nn;
273        mod = newmod;
274        memcpy(values, next, count * sizeof *values);
275    }
276    int64_t best = INT64_MAX;
277    for (int32_t i = 0; i < count; i++) {
278        int64_t v = values[i];
279        if (v < mu) {
280            int64_t k = (mu - v) / mod + ((mu - v) % mod != 0);
281            aoc_assert(k <= (INT64_MAX - v) / mod,
282                       "ghost answer exceeds signed 64 bits");
283            v += k * mod;
284        }
285        if (v < best) {
286            best = v;
287        }
288    }
289    return slice_from_i64(best);
290}
291
292slice part1(slice s) {
293    return solve(s, 1);
294}
295
296slice part2(slice s) {
297    return solve(s, 2);
298}
299
300const 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

A network and a repeating list of left/right instructions can look like a pathfinding problem. But we are never choosing a path: the next instruction determines the next edge. There is nothing for BFS to optimize. The local map has 758 nodes and 269 directions. Follow the instructions from AAA, wrap the direction index, and stop at ZZZ. That takes 18,023 transitions here, easily small enough to simulate directly.

There is one subtlety in deciding whether we are stuck. Returning to a node does not necessarily repeat our future, because we might be at a different position in the instruction list. The complete state is the pair of node and next instruction index. Only a repeated pair proves that the subsequent walk repeats. There are at most 758 × 269 = 203,902 such states locally, so we can detect an unreachable destination without walking forever.

Part two starts six ghosts and asks when all occupy some Z-ending node simultaneously. Simulating all six together is easy to write. It is also a trap in scale: the local first simultaneous arrival is about 14.45 trillion steps away. Even a hypothetical million complete six-ghost steps per second would need about 167 days. We need to describe what each ghost does repeatedly, rather than wait for the coincidence to happen.

Follow each ghost only until its complete state repeats. Record the initial nonrepeating stretch, the cycle length and every Z visit within the observed stretch. A cycle is a little timetable: after its prefix, certain offsets repeat forever. Across all six local ghosts, discovering these timetables takes 101,169 transitions. That is the useful experiment. It turns an impossible-looking wait into six short descriptions we can inspect.

The observations are unusually friendly. Prefixes have lengths 2–8. Cycle lengths are 11,567, 14,257, 16,409, 18,023, 19,637 and 21,251, and each walk has one Z visit per cycle. For every walk, that visit occurs at times divisible by its period, beginning with the period itself. Aha: on this input, simultaneous arrivals are common multiples of the six periods. Their least common multiple gives the first positive alignment after the prefixes.

It is important to earn that last sentence. “Take the LCM of the first Z hits” is not a general consequence of the story. A ghost could first arrive at time 2 and then every 4 steps, while another arrives at time 4 and then every 6. Their first common arrival is 10, not the LCM of 2 and 4. A cycle could also contain several Z nodes, or a Z visit could happen only before the cycle. Equal counts of A-ending and Z-ending names guarantee none of the convenient timing properties.

The implementation therefore retains the full timetables. It checks possible simultaneous arrivals before all prefixes have ended, then combines recurring schedules. A condition such as “time is 2 modulo 4” is joined with the next ghost's condition using the generalized Chinese remainder theorem. Two schedules are compatible only when their offset difference is divisible by the greatest common divisor of their periods. Compatible schedules repeat at the periods' LCM; multiple Z offsets create several candidate schedules. Finally, move each combined schedule forward past all prefixes and choose the earliest arrival.

This sounds more elaborate than the local answer needs, but it explains exactly which observation makes the local shortcut valid. The supported scope is 1,024 nodes, 512 directions, 32 starts, 64 observed Z hits per start and 256 combined residues, with at most two million walk transitions and checked signed 64-bit cycle arithmetic. The fun turn is from moving ghosts to aligning timetables. Detecting repetition is only the beginning; the phase of that repetition is what makes them meet.

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.