2024 / Day 24
Crossed Wires
Read the original puzzle on adventofcode.com ↗
The solution
solution.c
1#include "aoc.h"
2
3/* The local input is 4805 bytes, 313 lines, longest line 18. The circuit has 90
4 * primary bits and 222 gates: a 45-bit ripple-carry adder with four swapped
5 * output pairs. NODES = 512, GATES = 512, BITS = 63, SWAPS = 4 and WORK = 10000
6 * repair states bound it. Part 1 evaluates arbitrary acyclic Boolean circuits.
7 * Part 2 validates a complete ripple-adder topology and searches up to four
8 * disjoint output swaps: forced z-label fixes first, otherwise match the
9 * missing XOR/AND or OR input pair. Restart structural verification after each
10 * repair, and require every gate to participate in the recovered adder. This
11 * accepts smaller adders and fewer swaps; other circuit shapes or exhausted
12 * search receive a specific assertion. */
13
14static slice line(slice s, size_t *p) {
15 size_t b = *p;
16 while (*p < s.l && s.p[*p] != '\n') {
17 (*p)++;
18 }
19 size_t e = *p;
20 if (*p < s.l) {
21 (*p)++;
22 }
23 if (e > b && s.p[e - 1] == '\r') {
24 e--;
25 }
26 return (slice){s.p + b, e - b};
27}
28
29static uint64_t number(slice s, size_t *p, uint64_t limit) {
30 aoc_assert(*p < s.l && s.p[*p] >= '0' && s.p[*p] <= '9', "bad number");
31 uint64_t n = 0;
32 while (*p < s.l && s.p[*p] >= '0' && s.p[*p] <= '9') {
33 uint64_t d = s.p[(*p)++] - '0';
34 aoc_assert(d <= limit && n <= (limit - d) / 10, "number out of range");
35 n = n * 10 + d;
36 }
37 return n;
38}
39
40static void literal(slice s, size_t *p, const char *t) {
41 size_t n = strlen(t);
42 aoc_assert(*p <= s.l && n <= s.l - *p && memcmp(s.p + *p, t, n) == 0,
43 "bad syntax");
44 *p += n;
45}
46
47enum {
48 NODES = 512,
49 GATES = 512,
50 BITS = 63,
51 SWAPS = 4,
52 WORK = 10000,
53 CODES = 36 * 36 * 36
54};
55
56typedef struct {
57 int32_t a, b, out, op;
58} Gate;
59
60typedef struct {
61 int32_t kind, op, left, right, want;
62} Mismatch;
63
64static Gate gates[GATES];
65static int32_t lookup[CODES], producer[NODES], pair[SWAPS][2], inputs[2][BITS],
66 zs[BITS + 1];
67static uint16_t operation[3][NODES][NODES];
68static uint8_t value[NODES], known[NODES], used[NODES], gateused[GATES];
69static char names[NODES][4];
70static int32_t nn, ng, bits, ns, work;
71
72static int32_t digit(uint8_t c) {
73 if (c >= 'a' && c <= 'z') {
74 return c - 'a' + 10;
75 }
76 aoc_assert(c >= '0' && c <= '9',
77 "wire names need three lowercase letters or digits");
78 return c - '0';
79}
80
81static int32_t node(slice s, size_t *p) {
82 aoc_assert(*p + 3 <= s.l, "short wire name");
83 int32_t code = 0;
84 size_t start = *p;
85 for (int32_t i = 0; i < 3; i++) {
86 code = code * 36 + digit(s.p[(*p)++]);
87 }
88 if (!lookup[code]) {
89 aoc_assert(nn < NODES, "circuit exceeds 512 wires");
90 lookup[code] = ++nn;
91 memcpy(names[nn - 1], s.p + start, 3);
92 names[nn - 1][3] = 0;
93 }
94 return lookup[code] - 1;
95}
96
97static int32_t wire(char prefix, int32_t index) {
98 int32_t c = (prefix - 'a' + 10) * 36 * 36 + (index / 10) * 36 + index % 10;
99 return lookup[c] ? lookup[c] - 1 : -1;
100}
101
102static int32_t findgate(int32_t op, int32_t a, int32_t b) {
103 return a >= 0 && b >= 0 ? (int32_t)operation[op][a][b] - 1 : -1;
104}
105
106static int32_t mark(int32_t g) {
107 if (g < 0 || gateused[g]) {
108 return 0;
109 }
110 gateused[g] = 1;
111 return 1;
112}
113
114static Mismatch analyze(void) {
115 memset(gateused, 0, sizeof gateused);
116 int32_t p = findgate(2, inputs[0][0], inputs[1][0]),
117 carry = findgate(0, inputs[0][0], inputs[1][0]);
118 if (!mark(p) || !mark(carry)) {
119 return (Mismatch){-1, 0, 0, 0, 0};
120 }
121 if (gates[p].out != zs[0]) {
122 return (Mismatch){1, 0, p, 0, zs[0]};
123 }
124 for (int32_t bit = 1; bit < bits; bit++) {
125 int32_t pg = findgate(2, inputs[0][bit], inputs[1][bit]),
126 gg = findgate(0, inputs[0][bit], inputs[1][bit]);
127 if (!mark(pg) || !mark(gg)) {
128 return (Mismatch){-1, 0, 0, 0, 0};
129 }
130 int32_t a = gates[pg].out, b = gates[carry].out,
131 sum = findgate(2, a, b), t = findgate(0, a, b);
132 if (sum < 0 || t < 0) {
133 return (Mismatch){2, 2, pg, carry, 0};
134 }
135 if (!mark(sum) || !mark(t)) {
136 return (Mismatch){-1, 0, 0, 0, 0};
137 }
138 if (gates[sum].out != zs[bit]) {
139 return (Mismatch){1, 0, sum, 0, zs[bit]};
140 }
141 int32_t cg = findgate(1, gates[gg].out, gates[t].out);
142 if (cg < 0) {
143 return (Mismatch){2, 1, gg, t, 0};
144 }
145 if (!mark(cg)) {
146 return (Mismatch){-1, 0, 0, 0, 0};
147 }
148 carry = cg;
149 }
150 if (gates[carry].out != zs[bits]) {
151 return (Mismatch){1, 0, carry, 0, zs[bits]};
152 }
153 for (int32_t g = 0; g < ng; g++) {
154 if (!gateused[g]) {
155 return (Mismatch){-1, 0, 0, 0, 0};
156 }
157 }
158 return (Mismatch){0, 0, 0, 0, 0};
159}
160
161static void exchange(int32_t a, int32_t b) {
162 int32_t x = producer[a], y = producer[b];
163 gates[x].out = b;
164 gates[y].out = a;
165 producer[a] = y;
166 producer[b] = x;
167}
168
169static int32_t add_swap(int32_t a, int32_t b) {
170 if (a == b) {
171 return 1;
172 }
173 if (ns == SWAPS || producer[a] < 0 || producer[b] < 0 || used[a] ||
174 used[b]) {
175 return 0;
176 }
177 pair[ns][0] = a;
178 pair[ns][1] = b;
179 ns++;
180 used[a] = used[b] = 1;
181 exchange(a, b);
182 return 1;
183}
184
185static void undo(int32_t old) {
186 while (ns > old) {
187 ns--;
188 int32_t a = pair[ns][0], b = pair[ns][1];
189 exchange(a, b);
190 used[a] = used[b] = 0;
191 }
192}
193
194static int32_t repair(void);
195
196static inline __attribute__((always_inline)) int
197try_gate_orientations(Mismatch m, Gate *t, int32_t *answer_out) {
198 for (int32_t orientation = 0; orientation < 2; orientation++) {
199 int32_t x = orientation ? t->b : t->a, y = orientation ? t->a : t->b,
200 old = ns;
201 if (add_swap(gates[m.left].out, x) && add_swap(gates[m.right].out, y) &&
202 ns > old && repair()) {
203 {
204 *answer_out = 1;
205 return 1;
206 };
207 }
208 undo(old);
209 }
210
211 return 0;
212}
213
214static inline __attribute__((always_inline)) int
215try_repair_gates(Mismatch m, int32_t a, int32_t b, int32_t shared,
216 int32_t *answer_out) {
217 for (int32_t g = 0; g < ng; g++) {
218 Gate *t = &gates[g];
219 if (t->op != m.op) {
220 continue;
221 }
222 if (m.op == 2 && findgate(0, t->a, t->b) < 0) {
223 continue;
224 }
225 int32_t common = t->a == a || t->a == b || t->b == a || t->b == b;
226 if (common != shared) {
227 continue;
228 }
229 {
230 int32_t answer;
231 if (try_gate_orientations(m, t, &answer)) {
232 {
233 *answer_out = answer;
234 return 1;
235 };
236 }
237 }
238 }
239
240 return 0;
241}
242
243static int32_t repair(void) {
244 aoc_assert(++work <= WORK, "ripple repair exceeds 10000 search states");
245 Mismatch m = analyze();
246 if (m.kind == 0) {
247 return 1;
248 }
249 if (m.kind < 0 || ns == SWAPS) {
250 return 0;
251 }
252 if (m.kind == 1) {
253 int32_t old = ns;
254 if (add_swap(gates[m.left].out, m.want) && repair()) {
255 return 1;
256 }
257 undo(old);
258 return 0;
259 }
260 int32_t a = gates[m.left].out, b = gates[m.right].out;
261 for (int32_t shared = 1; shared >= 0; shared--) {
262 {
263 int32_t answer;
264 if (try_repair_gates(m, a, b, shared, &answer)) {
265 return answer;
266 }
267 }
268 }
269 return 0;
270}
271
272static inline __attribute__((always_inline)) void
273evaluate_ready_gates(uint8_t done[GATES], int32_t *count_ref,
274 int32_t *progress_ref) {
275 for (int32_t i = 0; i < ng; i++) {
276 Gate *g = &gates[i];
277 if (!done[i] && known[g->a] && known[g->b]) {
278 value[g->out] = g->op == 0 ? value[g->a] & value[g->b]
279 : g->op == 1 ? value[g->a] | value[g->b]
280 : value[g->a] ^ value[g->b];
281 known[g->out] = done[i] = 1;
282 (*count_ref)++;
283 (*progress_ref) = 1;
284 }
285 }
286}
287
288static inline __attribute__((always_inline)) int32_t
289check_input_wire(int32_t i, int32_t found) {
290 for (int32_t bit = 0; bit < bits; bit++) {
291 found |= inputs[0][bit] == i || inputs[1][bit] == i;
292 }
293
294 return found;
295}
296
297static inline __attribute__((always_inline)) int32_t
298insert_sorted_swapped_wire(int32_t list[SWAPS * 2], int32_t id, int32_t j) {
299 while (j && memcmp(names[list[j - 1]], names[id], 3) > 0) {
300 list[j] = list[j - 1];
301 j--;
302 }
303
304 return j;
305}
306
307static slice solve(slice s, int32_t part) {
308 memset(lookup, 0, sizeof lookup);
309 memset(known, 0, sizeof known);
310 nn = ng = 0;
311 for (int32_t i = 0; i < NODES; i++) {
312 producer[i] = -1;
313 }
314 size_t p = 0;
315 while (p < s.l) {
316 slice l = line(s, &p);
317 if (!l.l) {
318 break;
319 }
320 size_t q = 0;
321 int32_t id = node(l, &q);
322 literal(l, &q, ": ");
323 int32_t v = number(l, &q, 1);
324 aoc_assert(q == l.l && !known[id],
325 "duplicate primary wire or trailing value");
326 known[id] = 1;
327 value[id] = v;
328 }
329 while (p < s.l) {
330 slice l = line(s, &p);
331 aoc_assert(ng < GATES, "circuit exceeds 512 gates");
332 size_t q = 0;
333 int32_t a = node(l, &q);
334 literal(l, &q, " ");
335 int32_t op;
336 if (q < l.l && l.p[q] == 'A') {
337 literal(l, &q, "AND");
338 op = 0;
339 } else if (q < l.l && l.p[q] == 'O') {
340 literal(l, &q, "OR");
341 op = 1;
342 } else {
343 literal(l, &q, "XOR");
344 op = 2;
345 }
346 literal(l, &q, " ");
347 int32_t b = node(l, &q);
348 literal(l, &q, " -> ");
349 int32_t out = node(l, &q);
350 aoc_assert(q == l.l && !known[out] && producer[out] < 0,
351 "duplicate wire driver or trailing gate data");
352 gates[ng] = (Gate){a, b, out, op};
353 producer[out] = ng++;
354 }
355 aoc_assert(ng, "empty circuit");
356 if (part == 1) {
357 uint8_t done[GATES] = {0};
358 int32_t count = 0;
359 while (count < ng) {
360 int32_t progress = 0;
361 evaluate_ready_gates(done, &count, &progress);
362 aoc_assert(progress, "circuit has a cycle or undriven input");
363 }
364 uint64_t answer = 0;
365 int32_t countz = 0, gap = 0;
366 for (int32_t bit = 0; bit < 100; bit++) {
367 int32_t id = wire('z', bit);
368 if (id < 0) {
369 gap = 1;
370 continue;
371 }
372 aoc_assert(!gap && bit < 64 && known[id],
373 "z wires must be consecutive from z00 and fit 64 bits");
374 answer |= (uint64_t)value[id] << bit;
375 countz++;
376 }
377 aoc_assert(countz, "circuit has no z outputs");
378 char text[AOC_I64_TEXT];
379 char *end = aoc_u64_text(text, answer);
380 return slice_from_text(text, end - text);
381 }
382 bits = 0;
383 for (int32_t bit = 0; bit < BITS; bit++) {
384 int32_t x = wire('x', bit), y = wire('y', bit);
385 if (x < 0 || y < 0) {
386 break;
387 }
388 aoc_assert(known[x] && known[y],
389 "adder x/y wires must be primary inputs");
390 inputs[0][bits] = x;
391 inputs[1][bits] = y;
392 bits++;
393 }
394 aoc_assert(bits && ng == 2 + 5 * (bits - 1),
395 "repair requires a complete ripple-carry adder");
396 for (int32_t i = 0; i < nn; i++) {
397 if (known[i]) {
398 int32_t found = 0;
399 found = check_input_wire(i, found);
400 aoc_assert(found, "ripple adder has non-x/y primary wires");
401 }
402 }
403 for (int32_t bit = 0; bit <= bits; bit++) {
404 zs[bit] = wire('z', bit);
405 aoc_assert(zs[bit] >= 0 && producer[zs[bit]] >= 0,
406 "ripple adder is missing a z output");
407 }
408 memset(operation, 0, sizeof operation);
409 for (int32_t g = 0; g < ng; g++) {
410 Gate *t = &gates[g];
411 aoc_assert(!operation[t->op][t->a][t->b],
412 "ripple repair requires unique operation/input pairs");
413 operation[t->op][t->a][t->b] = operation[t->op][t->b][t->a] = g + 1;
414 }
415 memset(used, 0, sizeof used);
416 ns = work = 0;
417 aoc_assert(repair(),
418 "no ripple-adder repair within four disjoint output swaps");
419 if (!ns) {
420 return empty_slice;
421 }
422 int32_t list[SWAPS * 2];
423 for (int32_t i = 0; i < ns; i++) {
424 list[i * 2] = pair[i][0];
425 list[i * 2 + 1] = pair[i][1];
426 }
427 for (int32_t i = 1; i < ns * 2; i++) {
428 int32_t id = list[i], j = i;
429 j = insert_sorted_swapped_wire(list, id, j);
430 list[j] = id;
431 }
432 char text[SWAPS * 2 * 4];
433 char *end = text;
434 for (int32_t i = 0; i < ns * 2; i++) {
435 if (i) {
436 *end++ = ',';
437 }
438 memcpy(end, names[list[i]], 3);
439 end += 3;
440 }
441 return slice_from_text(text, end - text);
442}
443
444slice part1(slice s) {
445 return solve(s, 1);
446}
447
448slice part2(slice s) {
449 return solve(s, 2);
450}
451
452const 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#endifThe aha moment
Part one looks like a small logic-circuit exercise. The local device has 90 initial bits, 222 gates and 312 wires altogether. A gate becomes ready when both inputs are known. Evaluate it once, remember its output, and continue until everything has a value. The three operations are ordinary AND, OR and XOR; the real bookkeeping issue is that the input lines are not in dependency order.
A topological queue is available, but first estimate the simpler approach: repeatedly scan all unfinished gates and evaluate whichever are ready. In an acyclic circuit, a productive pass finishes at least one gate, so 222² = 49,284 gate inspections is already an upper bound here. The local ordering needs 47 passes, or 10,434 inspections. That is tiny. If a pass makes no progress, report an undriven wire or cycle instead of waiting forever. Finally assemble z00 as the least significant bit, z01 as the next, and so on.
Then the comfortable simulation problem turns into a repair job. The circuit should add the x and y numbers for every possible input, and four disjoint pairs of gate outputs have been exchanged. Making the supplied numbers add correctly is insufficient: an incorrect carry circuit may happen to work when its awkward input combination never occurs. Nor can we test all 2^90 input assignments. We need to discover what this circuit is supposed to be.
Trying four arbitrary output swaps is also hopeless. Choose eight of the 222 output wires, then pair them in 105 ways: about 13.5 quadrillion candidate repairs. Even a million complete candidates per second would take over four centuries. A faster Boolean evaluator will not rescue that approach. Time to step back and examine the gate pattern.
There are 89 XOR gates, 89 AND gates and 44 OR gates. For a 45-bit number, that is a very suggestive inventory: two gates for the lowest bit, then five gates for each of the remaining 44 bits. The repeated x_i XOR y_i and x_i AND y_i operations point toward a ripple-carry adder. This is an input-backed hypothesis we can check, rather than a structure promised by the words “adds two numbers.”
Derive one stage instead of memorizing a circuit diagram. Let p = x_i XOR y_i, meaning exactly one of the two input bits is set, and g = x_i AND y_i, meaning they already generate a carry. With incoming carry c, the sum bit is p XOR c. A carry leaves the stage if both inputs generated one, or if exactly one input passes the incoming carry onward: next_carry = g OR (p AND c). Bit zero has no incoming carry, and the last carry becomes the extra highest z bit. Now the jumble of wire names has a repeated grammatical structure.
Trace those stages from the least significant bit. If the correct sum gate is found but its output has the wrong z label, that label mismatch identifies a candidate swap directly. If the expected XOR/AND pair is missing, inspect pairs of gates sharing the same two inputs: one of the preceding outputs may have been renamed by a swap. A missing carry OR gives a similar constraint. Try compatible output-label repairs, prioritize candidates sharing an already expected input, and restart the structural trace after each attempt. Leave the gate operations and input labels alone; exchanging every occurrence of two names would describe a different modification.
On the local device, the successful trace encounters sum-label mismatches at bits 6 and 11, a missing input pair at bit 23, and another sum-label mismatch at bit 35. The repair search needs only five states, including its final successful verification. The overwhelming search space has collapsed because each earliest broken stage asks a specific local question. A few single-bit and carry-chain experiments could help diagnose a circuit by hand, but they would supply clues, not prove that every input works.
Here the final proof comes from recovering the complete adder structure, with every gate participating exactly once. The recurrence then establishes addition for all input bits by induction through the carry chain. Part one supports arbitrary acyclic circuits within 512 wires and 512 gates. Part two specifically searches complete ripple adders with up to 63 input bits, at most four disjoint output swaps and 10,000 repair states; the wire bound also applies. Smaller adders and fewer swaps are supported, while incompatible structures or exhausted search are explicitly refused. Recognizing the model earns the shortcut, and verifying that model earns confidence in the repair.
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.