2025 / Day 10
Factory
Read the original puzzle on adventofcode.com ↗
The solution
solution.c
1#include "aoc.h"
2
3/* The local input is 19748 bytes, 197 lines, longest line 211. The 197 machines
4 * have 4-10 counters, 2-13 buttons, and a largest joltage of 286. MACHINES=256,
5 * COUNTERS=12, BUTTONS=16 and JOLTAGE=1024 cover these measurements; identical
6 * buttons are merged. Part one enumerates binary press subsets (114940 subsets
7 * across the personal input). Part two uses the exact identity x=r+2y:
8 * enumerate subsets r with the required parity, subtract their increments,
9 * halve the target, and memoize the smaller vector. No floating-point
10 * elimination or rounding is involved. MEMO=65536 entries and WORK=2000000
11 * subset/branch visits bound computation per machine, with explicit refusal at
12 * either limit. Part one does not apply the irrelevant joltage limit. */
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 void spaces(slice s, size_t *p) {
30 while (*p < s.l && (s.p[*p] == ' ' || s.p[*p] == '\n' || s.p[*p] == '\r' ||
31 s.p[*p] == '\t')) {
32 (*p)++;
33 }
34}
35
36static uint64_t number(slice s, size_t *p, uint64_t limit) {
37 aoc_assert(*p < s.l && s.p[*p] >= '0' && s.p[*p] <= '9', "bad number");
38 uint64_t n = 0;
39 while (*p < s.l && s.p[*p] >= '0' && s.p[*p] <= '9') {
40 uint64_t d = s.p[(*p)++] - '0';
41 aoc_assert(d <= limit && n <= (limit - d) / 10, "number out of range");
42 n = n * 10 + d;
43 }
44 return n;
45}
46
47static void literal(slice s, size_t *p, const char *t) {
48 size_t n = strlen(t);
49 aoc_assert(*p <= s.l && n <= s.l - *p && memcmp(s.p + *p, t, n) == 0,
50 "bad syntax");
51 *p += n;
52}
53
54static int64_t checked_add(int64_t a, int64_t b) {
55 aoc_assert((b >= 0 && a <= INT64_MAX - b) || (b < 0 && a >= INT64_MIN - b),
56 "answer arithmetic overflow");
57 return a + b;
58}
59
60/* Measured part two: 139988 visits total, at most 12615 visits and 559 memo
61 * states for one machine. Epoch stamps avoid clearing each machine's table. */
62enum {
63 MACHINES = 256,
64 COUNTERS = 12,
65 BUTTONS = 16,
66 SUBSETS = 1 << BUTTONS,
67 PARITIES = 1 << COUNTERS,
68 JOLTAGE = 1024,
69 MEMO = 65536,
70 WORK = 2000000,
71 INF = UINT16_MAX
72};
73
74static uint16_t buttons[BUTTONS];
75static uint8_t increments[SUBSETS][COUNTERS], presses[SUBSETS];
76static int32_t next[SUBSETS], head[PARITIES], nc, nb;
77
78typedef struct {
79 uint16_t goal[COUNTERS], cost;
80
81} Entry;
82
83static Entry memo[MEMO];
84static uint16_t stamps[MEMO], epoch;
85static uint32_t visits, entries;
86
87static void tick(void) {
88 aoc_assert(++visits <= WORK,
89 "machine search exceeds 2000000 subset/branch visits");
90}
91
92static uint32_t hash_goal(const uint16_t *g) {
93 uint32_t h = 2166136261u;
94 for (int32_t k = 0; k < nc; k++) {
95 h = (h ^ g[k]) * 16777619u;
96 }
97 return h;
98}
99
100static int32_t slot(const uint16_t *g) {
101 uint32_t at = hash_goal(g) & (MEMO - 1);
102 while (stamps[at] == epoch &&
103 memcmp(memo[at].goal, g, (size_t)nc * sizeof(*g))) {
104 at = (at + 1) & (MEMO - 1);
105 }
106 return (int32_t)at;
107}
108
109static inline __attribute__((always_inline)) int32_t check_counter_increments(
110 const uint16_t *g, int32_t i, uint16_t half[COUNTERS], int32_t valid) {
111 for (int32_t k = 0; k < nc; k++) {
112 if (increments[i][k] > g[k]) {
113 valid = 0;
114 break;
115 }
116 half[k] = (uint16_t)((g[k] - increments[i][k]) / 2);
117 }
118
119 return valid;
120}
121
122static uint16_t minimum(const uint16_t *g) {
123 uint16_t lower = 0;
124 int32_t parity = 0;
125 for (int32_t k = 0; k < nc; k++) {
126 if (g[k] > lower) {
127 lower = g[k];
128 }
129 parity |= (g[k] & 1u) << k;
130 }
131 if (!lower) {
132 return 0;
133 }
134 int32_t at = slot(g);
135 if (stamps[at] == epoch) {
136 return memo[at].cost;
137 }
138 uint16_t best = INF;
139 for (int32_t i = head[parity]; i >= 0; i = next[i]) {
140 tick();
141 uint16_t half[COUNTERS];
142 int32_t valid = 1;
143 valid = check_counter_increments(g, i, half, valid);
144 if (!valid) {
145 continue;
146 }
147 uint16_t tail = minimum(half);
148 if (tail != INF) {
149 uint16_t cost = (uint16_t)(presses[i] + 2 * tail);
150 if (cost < best) {
151 best = cost;
152 }
153 if (best == lower) {
154 break;
155 }
156 }
157 }
158 at = slot(g);
159 aoc_assert(entries < MEMO * 3 / 4, "machine memo exceeds 49152 states");
160 stamps[at] = epoch;
161 memcpy(memo[at].goal, g, (size_t)nc * sizeof(*g));
162 memo[at].cost = best;
163 entries++;
164 return best;
165}
166
167static inline __attribute__((always_inline)) void
168read_button_counters(slice t, size_t *p_ref, uint16_t *mask_ref) {
169 for (;;) {
170 int32_t k = (int32_t)number(t, p_ref, (uint64_t)nc - 1);
171 aoc_assert(!((*mask_ref) & (1u << k)), "duplicate counter in a button");
172 (*mask_ref) |= (uint16_t)(1u << k);
173 if ((*p_ref) < t.l && t.p[(*p_ref)] == ',') {
174 (*p_ref)++;
175 continue;
176 }
177 break;
178 }
179}
180
181static inline __attribute__((always_inline)) int32_t
182check_duplicate_button(uint16_t mask, int32_t duplicate) {
183 for (int32_t i = 0; i < nb; i++) {
184 duplicate |= buttons[i] == mask;
185 }
186
187 return duplicate;
188}
189
190static inline __attribute__((always_inline)) void
191build_subset_increments(uint8_t counts[COUNTERS], int32_t bit, int32_t sign) {
192 for (int32_t k = 0; k < nc; k++) {
193 if (buttons[bit] & (1u << k)) {
194 counts[k] = (uint8_t)(counts[k] + sign);
195 }
196 }
197}
198
199static int64_t machine(slice t, int32_t part) {
200 size_t p = 0;
201 nc = nb = 0;
202 uint16_t lights = 0, goal[COUNTERS] = {0};
203 literal(t, &p, "[");
204 while (p < t.l && t.p[p] != ']') {
205 aoc_assert(nc < COUNTERS, "more than 12 machine counters");
206 uint8_t c = t.p[p++];
207 aoc_assert(c == '.' || c == '#', "bad light diagram");
208 if (c == '#') {
209 lights |= (uint16_t)(1u << nc);
210 }
211 nc++;
212 }
213 aoc_assert(nc > 0, "empty light diagram");
214 literal(t, &p, "]");
215 spaces(t, &p);
216 while (p < t.l && t.p[p] == '(') {
217 p++;
218 uint16_t mask = 0;
219 read_button_counters(t, &p, &mask);
220 literal(t, &p, ")");
221 int32_t duplicate = 0;
222 duplicate = check_duplicate_button(mask, duplicate);
223 if (!duplicate) {
224 aoc_assert(nb < BUTTONS, "more than 16 distinct machine buttons");
225 buttons[nb++] = mask;
226 }
227 spaces(t, &p);
228 }
229 aoc_assert(nb > 0, "machine has no buttons");
230 literal(t, &p, "{");
231 for (int32_t k = 0; k < nc; k++) {
232 uint64_t v = number(t, &p, part == 1 ? UINT64_MAX : JOLTAGE);
233 if (part == 2) {
234 goal[k] = (uint16_t)v;
235 }
236 if (k + 1 < nc) {
237 literal(t, &p, ",");
238 }
239 }
240 literal(t, &p, "}");
241 spaces(t, &p);
242 aoc_assert(p == t.l, "bad machine suffix");
243 visits = entries = 0;
244 memset(head, 255, sizeof(head));
245 uint8_t counts[COUNTERS] = {0};
246 uint16_t parity = 0;
247
248 int32_t best = INF;
249 for (uint32_t i = 0; i < (1u << nb); i++) {
250 tick();
251 uint32_t gray = i ^ (i >> 1);
252 if (i) {
253 int32_t bit = __builtin_ctz(i),
254 sign = (gray & (1u << bit)) ? 1 : -1;
255 parity ^= buttons[bit];
256 if (part == 2) {
257 build_subset_increments(counts, bit, sign);
258 }
259 }
260
261 int32_t cost = __builtin_popcount(gray);
262 if (parity == lights && cost < best) {
263 best = cost;
264 }
265 if (part == 2) {
266 memcpy(increments[i], counts, (size_t)nc);
267 presses[i] = (uint8_t)cost;
268 next[i] = head[parity];
269 head[parity] = (int32_t)i;
270 }
271 }
272 if (part == 1) {
273 aoc_assert(best != INF, "light diagram is unreachable");
274 return best;
275 }
276 epoch++;
277 uint16_t result = minimum(goal);
278 aoc_assert(result != INF, "joltage requirements are unreachable");
279 return result;
280}
281
282static slice solve(slice s, int32_t part) {
283 size_t p = 0;
284 int32_t n = 0;
285 int64_t total = 0;
286 epoch = 0;
287 memset(stamps, 0, sizeof(stamps));
288 while (p < s.l) {
289 aoc_assert(n++ < MACHINES, "more than 256 machines");
290 total = checked_add(total, machine(line(s, &p), part));
291 }
292 aoc_assert(n > 0, "no machines");
293 return slice_from_i64(total);
294}
295
296slice part1(slice s) {
297 return solve(s, 1);
298}
299
300slice part2(slice s) {
301 return solve(s, 2);
302}
303
304const 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
A Shiba Inu has eaten the important part of the manual, leaving us buttons and targets. The local factory has 197 machines, each with four to ten lights and two to thirteen distinct buttons. For part one, pressing a button toggles its listed lights. Button order does not matter, and pressing the same button twice cancels out. Any minimum solution therefore presses each button either zero times or once.
That makes exhaustive search a sensible first choice. A thirteen-button machine has only 8,192 subsets, and the entire local input has 114,940 subsets across all machines. Represent the lights and each button as bit masks, XOR the selected button masks, and keep the matching subset with the fewest presses. Breadth-first search over the light states would also work. Linear algebra over bits could establish reachability, but the requested minimum number of presses does not fall out of an arbitrary linear-system solution. At this scale, enumeration gets us there directly.
Part two flips the lever. Buttons now increment counters instead of toggling lights, so two presses no longer cancel. The largest local target is 286. Suddenly the binary-subset model has lost the repetitions we need. A BFS over bounded counter vectors can have more than 7 × 10^21 possible states for one local machine. Even independently bounding every button's count by the smallest target it touches leaves a local search box above 3 × 10^23 combinations. Most combinations may be impossible, but enumerating those boxes is not a useful plan.
The natural equations are A × x = target, where x contains nonnegative integer press counts. Ordinary elimination may reveal dependencies, but a fractional answer is unusable, and multiple feasible integer solutions can have different total costs. We need a way to preserve both exactness and the minimum. Before abandoning the toggle solution, ask what it still tells us about the counters.
Every press count has an odd part and an even part: x = r + 2y, where each entry of r is zero or one. For example, counts (5,2,7) become (1,0,1) + 2 × (2,1,3). Modulo two, the doubled part disappears. Therefore the buttons pressed an odd number of times must toggle exactly the parity pattern of the target counters. The first puzzle is hiding inside the second one. Use the target's odd/even pattern here, not the now-irrelevant indicator diagram.
Enumerate a binary button subset r with that required parity. Add up its actual counter increments, subtract them from the target, and discard the subset if it overshoots any counter. Every remaining component is even, so divide the residual vector by two. What remains is the same counter problem with a smaller target. If that smaller problem needs m presses, this branch costs the number of selected odd buttons plus 2m presses. Take the minimum over all parity-compatible subsets.
This is exact because every feasible press vector has one unique decomposition into its parity bits and its halved remainder. Conversely, a valid odd subset plus a solution of the halved target reconstructs a valid nonnegative press vector. We are neither rounding a continuous answer nor guessing which buttons deserve repetitions. The tempting shortcut of choosing the smallest odd subset immediately is unsafe: a slightly larger subset might leave a much cheaper halved problem. Compare complete branch costs.
Precompute the small subsets once per machine, grouping them by resulting parity, and memoize each smaller target vector. A maximum target of 286 permits only nine successive halvings before reaching zero. Different choices often reach the same smaller vector, so their future work is shared. There is also a useful stopping certificate: at least max(target) presses are needed, since one press increases any particular counter by at most one. If a branch achieves that lower bound, no further branch can improve it.
Measured across the local factory, subset preparation and recursive choices total 139,988 visits. The hardest single machine uses 12,615 visits and only 559 memoized nonzero targets. The giant counter space has become a sequence of small parity decisions. The implementation uses Gray-code subset enumeration to change one button at a time, but that is bookkeeping; the mathematical decomposition is the breakthrough.
Supported bounds are 256 machines, twelve counters, sixteen distinct buttons and part-two targets through 1,024. Identical buttons are merged. Each machine has a two-million subset/branch-visit budget and a 65,536-slot memo table capped at 49,152 stored targets, with explicit refusal at either limit. Part one does not impose the irrelevant joltage bound. We keep the two parts' different meanings clear while letting the first one's insight unlock the second.
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.