2023 / Day 20

Pulse Propagation

Read the original puzzle on adventofcode.com ↗

The solution

C11

solution.c

1#include "aoc.h"
2
3/* The local input is 792 bytes, 58 lines, longest line 33. The input has 58
4 * defined modules (48 flip-flops, nine conjunctions), four independent
5 * broadcaster branches and one final conjunction feeding rx. Those branches use
6 * 21 or 22 state bits including the final remembered input, cycle after a
7 * one-press transient with periods 3733, 3797, 3877 and 3917, and emit at most
8 * nine final-input pulses per press. MODULES = 128, OUTPUTS = 16, BRANCHES = 8,
9 * PHASES = 8192 and EVENTS = 16 bound exact branch-cycle records. FIFO order is
10 * depth then broadcaster-branch order when branches are independent. Combine
11 * all phase sets with generalized CRT at each high event, preserving remembered
12 * levels and intervening low pulses. Other topologies use direct simulation;
13 * WORK = 2000000 delivered pulses and PRESSES = 100000 bound that fallback.
14 * Exhausted storage/search is an explicit rejection. CRT enumeration is bounded
15 * by PHASE_WORK = 262144 phase examinations and CANDIDATE_EVENTS = 1024
16 * candidate high events. */
17
18static slice line(slice s, size_t *p) {
19    size_t b = *p;
20    while (*p < s.l && s.p[*p] != '\n') {
21        (*p)++;
22    }
23    size_t e = *p;
24    if (*p < s.l) {
25        (*p)++;
26    }
27    if (e > b && s.p[e - 1] == '\r') {
28        e--;
29    }
30    return (slice){s.p + b, e - b};
31}
32
33static void literal(slice s, size_t *p, const char *t) {
34    size_t n = strlen(t);
35    aoc_assert(*p <= s.l && n <= s.l - *p && memcmp(s.p + *p, t, n) == 0,
36               "bad syntax");
37    *p += n;
38}
39
40enum {
41    MODULES = 128,
42    OUTPUTS = 16,
43    BRANCHES = 8,
44    PHASES = 8192,
45    EVENTS = 16,
46    HASH = 16384,
47    QUEUE = 16384,
48    WORK = 2000000,
49    PRESSES = 100000,
50    COMBINATIONS = 256,
51    NAME = 16,
52    PHASE_WORK = 262144,
53    CANDIDATE_EVENTS = 1024
54};
55
56typedef struct {
57    char name[NAME];
58    int32_t type, defined, nout, out[OUTPUTS], nin, input[64];
59    uint64_t memory;
60    uint8_t on;
61} Module;
62
63typedef struct {
64    int32_t from, to, depth;
65    uint8_t high;
66} Pulse;
67
68typedef struct {
69    uint16_t depth;
70    uint8_t high;
71} Event;
72
73static Module modules[MODULES];
74static Pulse queue[QUEUE];
75static int32_t n, broadcaster, rx, work, parent, nb, owner[MODULES],
76    feeder[BRANCHES], mu[BRANCHES], period[BRANCHES], finished[BRANCHES];
77static int32_t phase_work;
78static uint64_t states[BRANCHES][HASH];
79static uint16_t first[BRANCHES][HASH];
80static uint8_t counts[BRANCHES][PHASES], remember[BRANCHES][PHASES];
81static Event events[BRANCHES][PHASES][EVENTS];
82
83static int32_t node(slice s, size_t *p) {
84    size_t b = *p;
85    while (*p < s.l && ((s.p[*p] >= 'a' && s.p[*p] <= 'z') ||
86                        (s.p[*p] >= '0' && s.p[*p] <= '9'))) {
87        (*p)++;
88    }
89    size_t len = *p - b;
90    aoc_assert(len && len < NAME, "bad module name or exceeds 15 bytes");
91    for (int32_t i = 0; i < n; i++) {
92        if (strlen(modules[i].name) == len &&
93            !memcmp(modules[i].name, s.p + b, len)) {
94            return i;
95        }
96    }
97    aoc_assert(n < MODULES, "more than 128 pulse modules");
98    memcpy(modules[n].name, s.p + b, len);
99    modules[n].name[len] = 0;
100    return n++;
101}
102
103static int32_t find(const char *name) {
104    size_t len = strlen(name);
105    for (int32_t i = 0; i < n; i++) {
106        if (strlen(modules[i].name) == len &&
107            !memcmp(modules[i].name, name, len)) {
108            return i;
109        }
110    }
111    return -1;
112}
113
114static inline __attribute__((always_inline)) int32_t
115find_conjunction_input(Pulse p, Module *m, int32_t k) {
116    while (k < m->nin && m->input[k] != p.from) {
117        k++;
118    }
119
120    return k;
121}
122
123static inline __attribute__((always_inline)) int32_t enqueue_output_pulses(
124    int32_t q, int32_t end, Pulse p, Module *m, int32_t value) {
125    for (int32_t i = 0; i < m->nout; i++) {
126        aoc_assert(end - q < QUEUE, "pulse queue exceeds 16384 events");
127        aoc_assert(p.depth < UINT16_MAX,
128                   "pulse propagation exceeds depth 65535");
129        queue[end++ % QUEUE] =
130            (Pulse){p.to, m->out[i], p.depth + 1, (uint8_t)value};
131    }
132
133    return end;
134}
135
136static int32_t press(int32_t t, int32_t record, int64_t *low, int64_t *high) {
137    int32_t q = 0, end = 1, received = 0;
138    queue[0] = (Pulse){-1, broadcaster, 0, 0};
139    if (record) {
140        for (int32_t b = 0; b < nb; b++) {
141            if (!finished[b]) {
142                counts[b][t] = 0;
143                remember[b][t] = (modules[parent].memory >> b) & 1;
144            }
145        }
146    }
147    while (q < end) {
148        Pulse p = queue[q++ % QUEUE];
149        aoc_assert(++work <= WORK,
150                   "pulse search exceeds 2000000 delivered events");
151        if (p.high) {
152            (*high)++;
153        } else {
154            (*low)++;
155        }
156        if (p.to == rx && !p.high) {
157            received = 1;
158        }
159        if (record && p.to == parent) {
160            int32_t b = owner[p.from];
161            aoc_assert(b >= 0 && b < nb,
162                       "pulse crossed certified branch boundary");
163            if (!finished[b]) {
164                int32_t k = counts[b][t]++;
165                aoc_assert(
166                    k < EVENTS && p.depth <= UINT16_MAX,
167                    "branch exceeds 16 final pulses per press or depth 65535");
168                events[b][t][k] = (Event){(uint16_t)p.depth, p.high};
169            }
170        }
171        Module *m = &modules[p.to];
172        if (!m->defined) {
173            continue;
174        }
175        int32_t value = p.high;
176        if (m->type == 1) {
177            if (p.high) {
178                continue;
179            }
180            m->on ^= 1;
181            value = m->on;
182        } else if (m->type == 2) {
183            int32_t k = 0;
184            k = find_conjunction_input(p, m, k);
185            aoc_assert(k < m->nin, "unknown conjunction input");
186            uint64_t bit = UINT64_C(1) << k;
187            if (p.high) {
188                m->memory |= bit;
189            } else {
190                m->memory &= ~bit;
191            }
192            uint64_t mask =
193                m->nin == 64 ? UINT64_MAX : (UINT64_C(1) << m->nin) - 1;
194            value = m->memory != mask;
195        }
196        end = enqueue_output_pulses(q, end, p, m, value);
197    }
198    return received;
199}
200
201static inline __attribute__((always_inline)) int
202find_receiver_parent(int32_t i, int32_t *answer_out) {
203    for (int32_t j = 0; j < modules[i].nout; j++) {
204        if (modules[i].out[j] == rx) {
205            if (parent >= 0) {
206                {
207                    *answer_out = 0;
208                    return 1;
209                };
210            }
211            parent = i;
212        }
213    }
214
215    return 0;
216}
217
218static inline __attribute__((always_inline)) int32_t find_pending_branch_node(
219    int32_t pending[MODULES], int32_t count, int32_t v, int32_t k) {
220    while (k < count && pending[k] != v) {
221        k++;
222    }
223
224    return k;
225}
226
227static inline __attribute__((always_inline)) int
228enqueue_branch_outputs(int32_t b, int32_t pending[MODULES], int32_t *count_ref,
229                       int32_t u, int32_t *answer_out) {
230    for (int32_t e = 0; e < modules[u].nout; e++) {
231        int32_t v = modules[u].out[e];
232        if (v == parent || !modules[v].defined) {
233            continue;
234        }
235        if (owner[v] < 0) {
236            int32_t k = 0;
237            k = find_pending_branch_node(pending, (*count_ref), v, k);
238            if (k == (*count_ref)) {
239                if ((*count_ref) == MODULES) {
240                    {
241                        *answer_out = 0;
242                        return 1;
243                    };
244                }
245                pending[(*count_ref)++] = v;
246            }
247        } else if (owner[v] != b) {
248            {
249                *answer_out = 0;
250                return 1;
251            };
252        }
253    }
254
255    return 0;
256}
257
258static inline __attribute__((always_inline)) int
259discover_branch_nodes(int32_t b, int32_t pending[MODULES], int32_t *count_ref,
260                      int32_t *answer_out) {
261    for (int32_t q = 0; q < (*count_ref); q++) {
262        int32_t u = pending[q];
263        if (u == parent || !modules[u].defined) {
264            continue;
265        }
266        if (u == broadcaster) {
267            {
268                *answer_out = 0;
269                return 1;
270            };
271        }
272        if (owner[u] >= 0) {
273            if (owner[u] != b) {
274                {
275                    *answer_out = 0;
276                    return 1;
277                };
278            }
279            continue;
280        }
281        owner[u] = b;
282        {
283            int32_t answer;
284            if (enqueue_branch_outputs(b, pending, count_ref, u, &answer)) {
285                {
286                    *answer_out = answer;
287                    return 1;
288                };
289            }
290        }
291    }
292
293    return 0;
294}
295
296static inline __attribute__((always_inline)) int
297count_branch_parent_edges(int32_t b, int32_t i, int32_t *answer_out) {
298    for (int32_t e = 0; e < modules[i].nout; e++) {
299        if (modules[i].out[e] == parent) {
300            if (feeder[b] >= 0) {
301                {
302                    *answer_out = 0;
303                    return 1;
304                };
305            }
306            feeder[b] = i;
307        }
308    }
309
310    return 0;
311}
312
313static inline __attribute__((always_inline)) int
314certify_branch_outputs(int32_t b, int32_t *bits_ref, int32_t *answer_out) {
315    for (int32_t i = 0; i < n; i++) {
316        if (owner[i] == b) {
317            (*bits_ref) += modules[i].type == 1   ? 1
318                           : modules[i].type == 2 ? modules[i].nin
319                                                  : 0;
320            {
321                int32_t answer;
322                if (count_branch_parent_edges(b, i, &answer)) {
323                    {
324                        *answer_out = answer;
325                        return 1;
326                    };
327                }
328            }
329        }
330    }
331
332    return 0;
333}
334
335static int32_t certify(void) {
336    if (rx < 0 || modules[rx].defined) {
337        return 0;
338    }
339    parent = -1;
340    for (int32_t i = 0; i < n; i++) {
341        {
342            int32_t answer;
343            if (find_receiver_parent(i, &answer)) {
344                return answer;
345            }
346        }
347    }
348    if (parent < 0 || modules[parent].type != 2) {
349        return 0;
350    }
351    Module *root = &modules[broadcaster];
352    nb = root->nout;
353    if (!nb || nb > BRANCHES || modules[parent].nin != nb) {
354        return 0;
355    }
356    for (int32_t i = 0; i < n; i++) {
357        owner[i] = -1;
358    }
359    for (int32_t b = 0; b < nb; b++) {
360        int32_t pending[MODULES], count = 1;
361        pending[0] = root->out[b];
362        {
363            int32_t answer;
364            if (discover_branch_nodes(b, pending, &count, &answer)) {
365                return answer;
366            }
367        }
368        int32_t bits = 1;
369        feeder[b] = -1;
370        {
371            int32_t answer;
372            if (certify_branch_outputs(b, &bits, &answer)) {
373                return answer;
374            }
375        }
376        if (bits > 64 || feeder[b] < 0) {
377            return 0;
378        }
379    }
380    for (int32_t i = 0; i < modules[parent].nout; i++) {
381        if (modules[modules[parent].out[i]].defined) {
382            return 0;
383        }
384    }
385    for (int32_t b = 0; b < nb; b++) {
386        modules[parent].input[b] = feeder[b];
387    }
388    return 1;
389}
390
391static uint64_t branch_state(int32_t b) {
392    uint64_t state = (modules[parent].memory >> b) & 1;
393    int32_t bits = 1;
394    for (int32_t i = 0; i < n; i++) {
395        if (owner[i] != b) {
396            continue;
397        }
398        Module *m = &modules[i];
399        if (m->type == 1) {
400            state |= (uint64_t)m->on << bits;
401            bits++;
402        } else if (m->type == 2) {
403            if (m->nin) {
404                state |= m->memory << bits;
405                bits += m->nin;
406            }
407        }
408    }
409    return state;
410}
411
412static int64_t gcd64(int64_t a, int64_t b) {
413    while (b) {
414        int64_t t = a % b;
415        a = b;
416        b = t;
417    }
418    return a;
419}
420
421static int64_t inverse(int64_t a, int64_t m) {
422    int64_t b = m, x = 1, y = 0;
423    while (b) {
424        int64_t q = a / b, t = a - q * b;
425        a = b;
426        b = t;
427        t = x - q * y;
428        x = y;
429        y = t;
430    }
431    return (x % m + m) % m;
432}
433
434static int32_t level_before(int32_t b, int32_t t, int32_t depth,
435                            int32_t candidate) {
436    int32_t value = remember[b][t];
437    for (int32_t i = 0; i < counts[b][t]; i++) {
438        Event e = events[b][t][i];
439        if (e.depth < depth || (e.depth == depth && b < candidate)) {
440            value = e.high;
441        } else {
442            break;
443        }
444    }
445    return value;
446}
447
448static inline __attribute__((always_inline)) int32_t find_existing_phase(
449    int64_t next[COMBINATIONS], int32_t nn, int64_t v, int32_t j) {
450    while (j < nn && next[j] != v) {
451        j++;
452    }
453
454    return j;
455}
456
457static inline __attribute__((always_inline)) int32_t
458merge_phase_residues(int64_t values[COMBINATIONS], int64_t next[COMBINATIONS],
459                     int64_t mod, int32_t count, int64_t g, int64_t m,
460                     int64_t newmod, int64_t inv, int32_t nn, int32_t t) {
461    for (int32_t i = 0; i < count; i++) {
462        int64_t delta = t - values[i];
463        if (delta % g) {
464            continue;
465        }
466        int64_t k = m == 1 ? 0 : (((delta / g) % m + m) % m * inv) % m,
467                v = (values[i] + mod * k) % newmod;
468        int32_t j = 0;
469        j = find_existing_phase(next, nn, v, j);
470        if (j == nn) {
471            aoc_assert(nn < COMBINATIONS,
472                       "pulse CRT exceeds 256 residue combinations");
473            next[nn++] = v;
474        }
475    }
476
477    return nn;
478}
479
480static inline __attribute__((always_inline)) int32_t merge_branch_phases(
481    int32_t cb, int32_t depth, int64_t values[COMBINATIONS],
482    int64_t next[COMBINATIONS], int64_t mod, int32_t count, int32_t b,
483    int64_t g, int64_t m, int64_t newmod, int64_t inv, int32_t nn) {
484    for (int32_t t = mu[b]; t < mu[b] + period[b]; t++) {
485        aoc_assert(++phase_work <= PHASE_WORK,
486                   "pulse CRT exceeds 262144 phase examinations");
487        if (!level_before(b, t, depth, cb)) {
488            continue;
489        }
490        nn = merge_phase_residues(values, next, mod, count, g, m, newmod, inv,
491                                  nn, t);
492    }
493
494    return nn;
495}
496
497static int64_t combine(int32_t cb, int32_t ct, int32_t depth, int32_t minimum) {
498    int64_t values[COMBINATIONS] = {ct % period[cb]}, next[COMBINATIONS],
499            mod = period[cb];
500    int32_t count = 1;
501    for (int32_t b = 0; b < nb; b++) {
502        if (b == cb) {
503            continue;
504        }
505        int64_t g = gcd64(mod, period[b]), m = period[b] / g;
506        aoc_assert(mod <= INT64_MAX / m,
507                   "pulse branch lcm exceeds signed 64 bits");
508        int64_t newmod = mod * m, inv = m == 1 ? 0 : inverse((mod / g) % m, m);
509        int32_t nn = 0;
510        nn = merge_branch_phases(cb, depth, values, next, mod, count, b, g, m,
511                                 newmod, inv, nn);
512        if (!nn) {
513            return INT64_MAX;
514        }
515        memcpy(values, next, nn * sizeof *values);
516        count = nn;
517        mod = newmod;
518    }
519    int64_t best = INT64_MAX;
520    for (int32_t i = 0; i < count; i++) {
521        int64_t v = values[i];
522        if (v < minimum) {
523            int64_t diff = minimum - v, k = diff / mod + (diff % mod != 0);
524            aoc_assert(k <= (INT64_MAX - v) / mod,
525                       "pulse answer exceeds signed 64 bits");
526            v += k * mod;
527        }
528        if (v < best) {
529            best = v;
530        }
531    }
532    return best;
533}
534
535static inline __attribute__((always_inline)) void
536check_unique_pulse_wire(Module *m, int32_t v) {
537    for (int32_t i = 0; i < m->nout; i++) {
538        aoc_assert(m->out[i] != v, "duplicate pulse wire");
539    }
540}
541
542static inline __attribute__((always_inline)) size_t
543read_module_outputs(slice l, size_t q, int32_t id) {
544    for (;;) {
545        Module *m = &modules[id];
546        aoc_assert(m->nout < OUTPUTS, "module exceeds 16 outputs");
547        int32_t v = node(l, &q);
548        check_unique_pulse_wire(m, v);
549        m->out[m->nout++] = v;
550        if (q == l.l) {
551            break;
552        }
553        literal(l, &q, ", ");
554    }
555
556    return q;
557}
558
559static inline __attribute__((always_inline)) void
560connect_module_inputs(int32_t i) {
561    for (int32_t j = 0; j < modules[i].nout; j++) {
562        Module *m = &modules[modules[i].out[j]];
563        if (m->type == 2) {
564            aoc_assert(m->nin < 64, "conjunction exceeds 64 inputs");
565            m->input[m->nin++] = i;
566        }
567    }
568}
569
570static inline __attribute__((always_inline)) uint32_t
571find_branch_state_slot(int32_t b, uint64_t state, uint32_t slot) {
572    while (first[b][slot] && states[b][slot] != state) {
573        slot = (slot + 1) & (HASH - 1);
574    }
575
576    return slot;
577}
578
579static inline __attribute__((always_inline)) int32_t
580track_branch_cycles(int32_t t, int32_t done) {
581    for (int32_t b = 0; b < nb; b++) {
582        if (finished[b]) {
583            continue;
584        }
585        uint64_t state = branch_state(b);
586        uint32_t slot = (uint32_t)((state ^ (state >> 32)) *
587                                   UINT64_C(11400714819323198485)) &
588                        (HASH - 1);
589        slot = find_branch_state_slot(b, state, slot);
590        if (first[b][slot]) {
591            mu[b] = first[b][slot] - 1;
592            period[b] = t - mu[b];
593            finished[b] = 1;
594            done++;
595        } else {
596            first[b][slot] = t + 1;
597            states[b][slot] = state;
598        }
599    }
600
601    return done;
602}
603
604static inline __attribute__((always_inline)) void
605record_cycle_events(int32_t t, int64_t *answer_ref, int32_t *candidates_ref,
606                    int32_t b, int32_t phase) {
607    for (int32_t e = 0; e < counts[b][phase]; e++) {
608        Event event = events[b][phase][e];
609        if (event.high) {
610            aoc_assert(++(*candidates_ref) <= CANDIDATE_EVENTS,
611                       "pulse cycle exceeds 1024 high-event candidates");
612            int64_t candidate = combine(b, phase, event.depth, t);
613            if (candidate < (*answer_ref)) {
614                (*answer_ref) = candidate;
615            }
616        }
617    }
618}
619
620static inline __attribute__((always_inline)) void
621record_branch_phases(int32_t t, int64_t *answer_ref, int32_t *candidates_ref,
622                     int32_t b) {
623    for (int32_t phase = mu[b]; phase < mu[b] + period[b]; phase++) {
624        record_cycle_events(t, answer_ref, candidates_ref, b, phase);
625    }
626}
627
628static slice solve(slice s, int32_t part) {
629    memset(modules, 0, sizeof modules);
630    n = work = phase_work = 0;
631    size_t p = 0;
632    while (p < s.l) {
633        slice l = line(s, &p);
634        size_t q = 0;
635        int32_t type = 0;
636        if (q < l.l && (l.p[q] == '%' || l.p[q] == '&')) {
637            type = l.p[q++] == '%' ? 1 : 2;
638        }
639        int32_t id = node(l, &q);
640        aoc_assert(!modules[id].defined, "duplicate pulse module");
641        modules[id].defined = 1;
642        modules[id].type = type;
643        literal(l, &q, " -> ");
644        q = read_module_outputs(l, q, id);
645    }
646    broadcaster = find("broadcaster");
647    rx = find("rx");
648    aoc_assert(broadcaster >= 0 && modules[broadcaster].type == 0,
649               "missing broadcaster");
650    for (int32_t i = 0; i < n; i++) {
651        aoc_assert(!modules[i].defined || modules[i].type || i == broadcaster,
652                   "only broadcaster may lack a module prefix");
653        connect_module_inputs(i);
654    }
655    int64_t low = 0, high = 0;
656    if (part == 1) {
657        for (int32_t t = 0; t < 1000; t++) {
658            press(t, 0, &low, &high);
659        }
660        return slice_from_i64(low * high);
661    }
662    aoc_assert(rx >= 0, "network has no rx receiver");
663    int32_t certified = certify();
664    if (!certified) {
665        for (int32_t t = 0; t < PRESSES; t++) {
666            if (press(t, 0, &low, &high)) {
667                return slice_from_i64(t + 1);
668            }
669        }
670        aoc_assert(0, "rx search exceeds 100000 button presses");
671    }
672    memset(first, 0, sizeof first);
673    memset(finished, 0, sizeof finished);
674    int32_t t = 0, done = 0;
675    for (; t < PHASES; t++) {
676        done = track_branch_cycles(t, done);
677        if (done == nb) {
678            break;
679        }
680        if (press(t, 1, &low, &high)) {
681            return slice_from_i64(t + 1);
682        }
683    }
684    aoc_assert(done == nb, "branch cycle not found within 8192 states");
685    int64_t answer = INT64_MAX;
686    int32_t candidates = 0;
687    for (int32_t b = 0; b < nb; b++) {
688        record_branch_phases(t, &answer, &candidates, b);
689    }
690    aoc_assert(answer != INT64_MAX,
691               "rx never receives a low pulse in certified branch cycles");
692    aoc_assert(answer < INT64_MAX, "pulse answer exceeds signed 64 bits");
693    return slice_from_i64(answer + 1);
694}
695
696slice part1(slice s) {
697    return solve(s, 1);
698}
699
700slice part2(slice s) {
701    return solve(s, 2);
702}
703
704const 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 modules are small, but their timing rules are precise. A flip-flop reacts only to low pulses. A conjunction remembers the latest pulse from each input, updates that memory for the arriving pulse, then emits its result immediately. Pulses are processed in the order they were sent. Before looking for a shortcut, build a faithful FIFO simulation with events containing sender, receiver and level. The sender matters because a conjunction updates one particular input's memory.

The local network has 58 defined modules: 48 flip-flops, nine conjunctions and the broadcaster, connected by 109 outgoing wires. A thousand button presses deliver 63,587 pulses, including 16,971 low and 46,616 high. That is small. Count every delivered pulse, including the button's pulse and pulses reaching an undefined output sink, and completely drain the queue before the next press. Part one is an excellent case for direct simulation.

The second public example quietly teaches the dangerous detail. A conjunction can emit low and then high within the same press as different inputs change. Looking only at module states after the queue drains misses that brief success. Replacing the queue with a stack also changes which remembered input levels coexist. This puzzle's event ordering is part of its logic, not an implementation preference.

Part two asks for the first low pulse to rx, which may be vastly later than the first thousand presses. First inspect the wiring near rx. Locally it has one predecessor, a conjunction, whose four inputs come from four independent branches of the broadcaster. Each branch contains 14 modules, and the final conjunction does not feed back into them. That structural observation offers a way to avoid waiting for the entire network to repeat at once.

A branch's future is determined by its flip-flops, its conjunction memories and the final conjunction's remembered level for that branch. The local branch states need only 21 or 22 bits. Recording exact states at press boundaries finds a one-press transient followed by periods 3,733, 3,797, 3,877 and 3,917. All four cycles are discovered after 3,918 simulated presses and 249,928 delivered events. Their combined period is about 215 trillion presses; even a million presses per second would need nearly seven years to enumerate one combined period. The short individual cycles are the useful scale.

Aha, we can align repeating branch schedules arithmetically. But there is a trap inside the shortcut: “take the LCM of the first high pulses” is not enough justification. Conjunction memory persists between presses, branches can send several pulses during one press, and an intervening low can undo an earlier high. Locally a branch sends as many as nine pulses to the final conjunction in a single press. Assuming one pulse per branch would contradict the actual trace.

Record each branch phase's starting remembered level and its ordered pulses to the final conjunction. A low output can occur only just after some arriving high pulse makes every remembered input high. Treat each such high event as a candidate, and ask which phases of every other branch leave its remembered level high at precisely that event. Earlier low pulses matter; later ones do not undo a success that has already happened.

Because the branches are independent, FIFO order can be reconstructed by propagation depth, then broadcaster branch order, while preserving event order within a branch. The implementation certifies that wiring structure before using it. Each candidate produces allowed phase residues for the branches. Generalized Chinese remainder arithmetic combines compatible residues, including non-coprime periods, and gives the earliest press beyond the already simulated prefix. The direct prefix simulation has already checked for earlier success. This is an exact schedule calculation under the certified structure, not an extrapolation from a few promising pulse gaps.

Other network shapes retain bounded direct simulation. The implementation permits 128 modules, 16 outputs per module, 64 inputs per conjunction and a queue of 16,384 pulses, with a two-million-event work cap. The branch method allows eight branches, 8,192 recorded phases, 16 final-input events per phase and 256 combined residues; it also bounds phase examinations and candidate high events. Fallback simulation stops after 100,000 presses or the event cap. The breakthrough comes in two stages: discover independent repetition in the wiring, then preserve enough timing information to combine it without losing the very pulse we are looking for.

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.