2016 / Day 10
Balance Bots
Read the original puzzle on adventofcode.com ↗
The solution
solution.c
1#include "aoc.h"
2
3#include <string.h>
4
5/* 2016 day 10. Factory of bots: each bot fires the moment it holds
6 * two chips, giving the lower to one target and the higher to
7 * another. Firing is driven by a pending list, so a ready bot always
8 * empties before its next arrival and no bot ever transiently holds
9 * three chips.
10 *
11 * Part 1 hardcodes the story's pair: which bot compares 61 with 17
12 * ("no bot compares 61 and 17" outside the real factory, so the
13 * puzzle example refuses part 1). Part 2 multiplies the single chip
14 * in each of outputs 0, 1, and 2 — the story promises exactly one
15 * there ("outputs 0 1 2 need one chip each" otherwise).
16 *
17 * Bounds: at most BOTMAX = 256 bots (real max id 209), OUTMAX = 64
18 * output bins (real max id 20) holding CHIPMAX = 4 chips each, at
19 * most VALMAX = 256 value chips (real: 21), values at most 1e6, and
20 * at most MAXFIRE = 4000 comparisons (the real factory settles after
21 * 210; a routing loop is refused with "factory does not settle").
22 */
23
24enum { BOTMAX = 256 };
25
26enum { OUTMAX = 64 };
27
28enum { CHIPMAX = 4 };
29
30enum { VALMAX = 256 };
31
32enum { MAXFIRE = 4000 };
33
34enum { MAXPEND = VALMAX + 2 * MAXFIRE };
35
36enum { VALUECAP = 1000000 };
37
38struct rule {
39 int8_t lokind; /* 0 = bot, 1 = output */
40 int16_t loidx;
41 int8_t hikind;
42 int16_t hiidx;
43};
44
45struct pe {
46 int b;
47 int v;
48};
49
50static struct rule rules[BOTMAX];
51static uint8_t hasrule[BOTMAX];
52static int bcnt[BOTMAX];
53static int bchip[BOTMAX][2];
54static int outs[OUTMAX][CHIPMAX];
55static int ocnt[OUTMAX];
56static struct pe pend[MAXPEND];
57static int npend;
58static int head;
59static int fires;
60static int watch;
61
62/* AT(s, i, end, lit) matches the literal with its true length; the
63 * length is never hand-counted.
64 */
65#define AT(s, i, end, lit) at((s), (i), (end), (lit), sizeof(lit) - 1)
66
67static int at(const uint8_t *s, size_t *i, size_t end, const char *lit,
68 size_t n) {
69 if (*i + n <= end && memcmp(s + *i, lit, n) == 0) {
70 *i += n;
71 return 1;
72 }
73 return 0;
74}
75
76static int pnum(const uint8_t *s, size_t *i, size_t end, int *out) {
77 int v = 0;
78 int nd = 0;
79
80 while (*i < end && s[*i] >= '0' && s[*i] <= '9') {
81 nd++;
82 aoc_assert(nd <= 9, "bad instruction");
83 v = v * 10 + (s[*i] - '0');
84 (*i)++;
85 }
86 if (nd == 0) {
87 return 0;
88 }
89 *out = v;
90 return 1;
91}
92
93static void target(const uint8_t *s, size_t *i, size_t end, int8_t *kind,
94 int16_t *idx) {
95 int v = 0;
96
97 if (AT(s, i, end, "bot ")) {
98 *kind = 0;
99 } else {
100 aoc_assert(AT(s, i, end, "output "), "bad instruction");
101 *kind = 1;
102 }
103 aoc_assert(pnum(s, i, end, &v), "bad instruction");
104 if (*kind == 0) {
105 aoc_assert(v < BOTMAX, "bot id out of range");
106 } else {
107 aoc_assert(v < OUTMAX, "output id out of range");
108 }
109 *idx = (int16_t)v;
110}
111
112static void push(int b, int v) {
113 aoc_assert(npend < MAXPEND, "factory does not settle");
114 pend[npend].b = b;
115 pend[npend].v = v;
116 npend++;
117}
118
119static inline __attribute__((always_inline)) size_t
120find_instruction_end(slice input, size_t eol) {
121 while (eol < input.l && input.p[eol] != '\n') {
122 eol++;
123 }
124
125 return eol;
126}
127
128static void run(slice input) {
129 size_t i = 0;
130
131 memset(rules, 0, sizeof rules);
132 memset(hasrule, 0, sizeof hasrule);
133 memset(bcnt, 0, sizeof bcnt);
134 memset(bchip, 0, sizeof bchip);
135 memset(outs, 0, sizeof outs);
136 memset(ocnt, 0, sizeof ocnt);
137 npend = 0;
138 head = 0;
139 fires = 0;
140 watch = -1;
141
142 aoc_assert(input.l <= 65536, "input too long");
143 while (i < input.l) {
144 size_t eol = i;
145 eol = find_instruction_end(input, eol);
146 if (eol > i && input.p[eol - 1] == '\r') {
147 eol--;
148 }
149 if (eol == i) {
150 i++;
151 continue;
152 }
153 if (AT(input.p, &i, eol, "value ")) {
154 int v = 0;
155 int b = 0;
156 aoc_assert(pnum(input.p, &i, eol, &v), "bad instruction");
157 aoc_assert(v <= VALUECAP, "value too big");
158 aoc_assert(AT(input.p, &i, eol, " goes to bot "),
159 "bad instruction");
160 aoc_assert(pnum(input.p, &i, eol, &b), "bad instruction");
161 aoc_assert(i == eol, "bad instruction");
162 aoc_assert(b < BOTMAX, "bot id out of range");
163 aoc_assert(npend < VALMAX, "too many chips");
164 push(b, v);
165 } else {
166 int b = 0;
167 aoc_assert(AT(input.p, &i, eol, "bot "), "bad instruction");
168 aoc_assert(pnum(input.p, &i, eol, &b), "bad instruction");
169 aoc_assert(b < BOTMAX, "bot id out of range");
170 aoc_assert(AT(input.p, &i, eol, " gives low to "),
171 "bad instruction");
172 target(input.p, &i, eol, &rules[b].lokind, &rules[b].loidx);
173 aoc_assert(AT(input.p, &i, eol, " and high to "),
174 "bad instruction");
175 target(input.p, &i, eol, &rules[b].hikind, &rules[b].hiidx);
176 aoc_assert(i == eol, "bad instruction");
177 aoc_assert(!hasrule[b], "duplicate bot rule");
178 hasrule[b] = 1;
179 }
180 i = eol;
181 if (i < input.l) {
182 i++;
183 }
184 }
185
186 while (head < npend) {
187 int b = pend[head].b;
188 int v = pend[head].v;
189 int lo, hi;
190 head++;
191 aoc_assert(bcnt[b] < 2, "bot holds three chips");
192 bchip[b][bcnt[b]] = v;
193 bcnt[b]++;
194 if (bcnt[b] < 2) {
195 continue;
196 }
197 lo = bchip[b][0];
198 hi = bchip[b][1];
199 if (lo > hi) {
200 int t = lo;
201 lo = hi;
202 hi = t;
203 }
204 bcnt[b] = 0;
205 fires++;
206 aoc_assert(fires <= MAXFIRE, "factory does not settle");
207 aoc_assert(hasrule[b], "bot has no rule");
208 if ((lo == 61 && hi == 17) || (lo == 17 && hi == 61)) {
209 if (watch < 0) {
210 watch = b;
211 }
212 }
213 if (rules[b].lokind == 0) {
214 push(rules[b].loidx, lo);
215 } else {
216 int o = rules[b].loidx;
217 aoc_assert(ocnt[o] < CHIPMAX, "output bin overflow");
218 outs[o][ocnt[o]++] = lo;
219 }
220 if (rules[b].hikind == 0) {
221 push(rules[b].hiidx, hi);
222 } else {
223 int o = rules[b].hiidx;
224 aoc_assert(ocnt[o] < CHIPMAX, "output bin overflow");
225 outs[o][ocnt[o]++] = hi;
226 }
227 }
228}
229
230slice part1(slice input) {
231 run(input);
232 aoc_assert(watch >= 0, "no bot compares 61 and 17");
233 return slice_from_i64(watch);
234}
235
236slice part2(slice input) {
237 int64_t product;
238
239 run(input);
240 aoc_assert(ocnt[0] == 1 && ocnt[1] == 1 && ocnt[2] == 1,
241 "outputs 0 1 2 need one chip each");
242 product = (int64_t)outs[0][0] * outs[1][0] * outs[2][0];
243 return slice_from_i64(product);
244}
245
246const struct aoc_method aoc_methods[] = {
247 {0, 0},
248};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
Bots zooming around a factory can make us imagine clocks, threads, and everything happening at once. Freeze the scene and watch one bot. With one chip, it does nothing. A second chip arrives, and now it acts. That arrival is all the clock we need. The local factory has 210 bot rules but only 21 starting chips, valued from 2 to 73. Follow the chips and let each arrival tell us whether there is work to do.
There is an early snag if we execute instructions as we read them: a chip can arrive before we have seen its bot's routing rule. The document is a factory description, not a timeline. Read the whole configuration first. Then queue deliveries, store a bot's first chip, and let its second trigger a comparison. Empty the bot before scheduling its outgoing chips. Output bins simply keep what arrives. The bustling factory becomes a sequence we can trace one event at a time.
A simpler repeated scan for ready bots would also be affordable here. The measured factory makes only 210 comparisons before settling, so even hundreds of scans over 210 bots would be modest. The queue is useful because it expresses the cause of each action and avoids searching for work. It also makes a good debugging trace: a bot receives its second chip, compares a pair, and sends two chips onward. Empty it before those deliveries can return to it.
Part 1 is a question about the journey, not the final arrangement. Record the bot comparing 17 and 61 at the moment of comparison. Looking only at the final bins loses that event. The story's example watches 2 and 5 to illustrate the mechanism, but the actual question fixes 17 and 61; this solver deliberately refuses the example for part 1 because that comparison never occurs.
Part 2 sends us to the output bins. A welcome change: the machine we just built already knows how to get there. Continue until the queue is empty and inspect bins 0, 1, and 2; the example gives 5 × 2 × 3 = 30. We observed an event during part 1 and the final state during part 2. Here the implementation requires exactly one chip in each of those bins; the story asks for one chip from each, and this is the supported interpretation.
The measured IDs reach bot 209 and output 20. The implementation supports bot IDs below 256, output IDs below 64, at most 256 starting chips, values through one million, and four chips per output bin. It allows 4,000 comparisons, well above the measured 210, then refuses a factory that does not settle. Input text is capped at 65,536 characters. A queue alone would not prevent an arbitrary routing cycle from running forever; the comparison bound supplies that guarantee.
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.