2016 / Day 23
Safe Cracking
Read the original puzzle on adventofcode.com ↗
The solution
solution.c
1#include "aoc.h"
2
3/* At most 256 instructions; literal magnitudes <= 1e9, registers stay
4 * inside +/-1e12. Recognize loops at execution time so toggles and jumps
5 * into a loop's interior retain their original semantics. */
6enum { PROGMAX = 256, STEPMAX = 1000000 };
7
8static const int64_t REGCAP = 1000000000000LL;
9
10enum { CPY, INC, DEC, JNZ, TGL, OUT };
11
12struct arg {
13 int8_t reg;
14 int64_t val;
15};
16
17struct ins {
18 uint8_t op;
19 struct arg x, y;
20};
21static struct ins program[PROGMAX], code[PROGMAX];
22static int nins;
23
24static struct arg operand(slice line, size_t *i) {
25 while (*i < line.l && (line.p[*i] == ' ' || line.p[*i] == '\t')) {
26 (*i)++;
27 }
28 size_t start = *i;
29 while (*i < line.l && line.p[*i] != ' ' && line.p[*i] != '\t') {
30 (*i)++;
31 }
32 size_t end = *i;
33 aoc_assert(end > start, "missing operand");
34 struct arg a = {-1, 0};
35 if (end - start == 1 && line.p[start] >= 'a' && line.p[start] <= 'd') {
36 a.reg = (int8_t)(line.p[start] - 'a');
37 return a;
38 }
39 int neg = line.p[start] == '-';
40 if (neg || line.p[start] == '+') {
41 start++;
42 }
43 aoc_assert(start < end, "bad operand");
44 for (; start < end; start++) {
45 uint8_t c = line.p[start];
46 aoc_assert(c >= '0' && c <= '9', "bad operand");
47 aoc_assert(a.val <= (1000000000 - (c - '0')) / 10, "operand too large");
48 a.val = a.val * 10 + (c - '0');
49 }
50 if (neg) {
51 a.val = -a.val;
52 }
53 return a;
54}
55
56static inline __attribute__((always_inline)) size_t
57find_instruction_end(slice in, size_t end) {
58 while (end < in.l && in.p[end] != '\n') {
59 end++;
60 }
61
62 return end;
63}
64
65static inline __attribute__((always_inline)) size_t
66skip_instruction_spaces(size_t len, slice line, size_t p) {
67 while (p < len && (line.p[p] == ' ' || line.p[p] == '\t')) {
68 p++;
69 }
70
71 return p;
72}
73
74static inline __attribute__((always_inline)) size_t scan_opcode(size_t len,
75 slice line,
76 size_t p) {
77 while (p < len && line.p[p] != ' ' && line.p[p] != '\t') {
78 p++;
79 }
80
81 return p;
82}
83
84static inline __attribute__((always_inline)) void
85identify_opcode(slice line, size_t op, const char *names[], int *k_ref) {
86 for ((*k_ref) = 0; (*k_ref) < 6; (*k_ref)++) {
87 if (!memcmp(line.p + op, names[(*k_ref)], 3)) {
88 break;
89 }
90 }
91}
92
93static inline __attribute__((always_inline)) size_t
94skip_operand_spaces(size_t len, slice line, size_t p) {
95 while (p < len && (line.p[p] == ' ' || line.p[p] == '\t')) {
96 p++;
97 }
98
99 return p;
100}
101
102static void load(slice in) {
103 size_t i = 0;
104 nins = 0;
105 aoc_assert(in.l <= 65536, "input too long");
106 while (i < in.l) {
107 size_t end = i;
108 end = find_instruction_end(in, end);
109 size_t len = end - i;
110 if (len && in.p[i + len - 1] == '\r') {
111 len--;
112 }
113 slice line = {in.p + i, len};
114 size_t p = 0;
115 p = skip_instruction_spaces(len, line, p);
116 if (p < len) {
117 size_t op = p;
118 p = scan_opcode(len, line, p);
119 aoc_assert(p - op == 3, "bad instruction");
120 struct ins x = {0};
121 const char *names[] = {"cpy", "inc", "dec", "jnz", "tgl", "out"};
122 int k;
123 identify_opcode(line, op, names, &k);
124 aoc_assert(k < 6, "bad instruction");
125 x.op = (uint8_t)k;
126 x.x = operand(line, &p);
127 x.y.reg = -1;
128 if (k == CPY || k == JNZ) {
129 x.y = operand(line, &p);
130 }
131 p = skip_operand_spaces(len, line, p);
132 aoc_assert(p == len, "bad instruction");
133 aoc_assert(nins < PROGMAX, "program too long");
134 program[nins++] = x;
135 }
136 i = end < in.l ? end + 1 : end;
137 }
138 aoc_assert(nins > 0, "empty program");
139}
140
141static int64_t value(struct arg a, const int64_t r[4]) {
142 return a.reg < 0 ? a.val : r[a.reg];
143}
144
145static int literal(struct arg a, int64_t v) {
146 return a.reg < 0 && a.val == v;
147}
148
149static void add(int64_t *a, int64_t b) {
150 aoc_assert(b >= -REGCAP && b <= REGCAP && *a <= REGCAP - b &&
151 *a >= -REGCAP - b,
152 "register exceeds cap");
153 *a += b;
154}
155
156/* Only positive, terminating add/multiply idioms, with non-aliased
157 * counters and a source that stays constant throughout the loop. */
158static int optimize(int pc, int64_t r[4]) {
159 struct ins *p = code + pc;
160 /* Exact division idiom: consume pairs from B, increment A, leave
161 * C as 2-remainder. All branch operands and register aliases matter. */
162 if (pc + 7 < nins && p[0].op == CPY && literal(p[0].x, 2) &&
163 p[1].op == JNZ && literal(p[1].y, 2) && p[2].op == JNZ &&
164 literal(p[2].x, 1) && literal(p[2].y, 6) && p[3].op == DEC &&
165 p[4].op == DEC && p[5].op == JNZ && literal(p[5].y, -4) &&
166 p[6].op == INC && p[7].op == JNZ && literal(p[7].x, 1) &&
167 literal(p[7].y, -7)) {
168 int a = p[6].x.reg, b = p[3].x.reg, c = p[4].x.reg;
169 if (a >= 0 && b >= 0 && c >= 0 && a != b && a != c && b != c &&
170 p[0].y.reg == c && p[1].x.reg == b && p[5].x.reg == c &&
171 r[b] >= 0) {
172 add(&r[a], r[b] / 2);
173 r[c] = 2 - r[b] % 2;
174 r[b] = 0;
175 return 8;
176 }
177 }
178 if (pc + 5 < nins && p[0].op == CPY && p[1].op == INC && p[2].op == DEC &&
179 p[3].op == JNZ && p[4].op == DEC && p[5].op == JNZ) {
180 int a = p[1].x.reg, b = p[2].x.reg, c = p[4].x.reg;
181 if (a >= 0 && b >= 0 && c >= 0 && a != b && a != c && b != c &&
182 p[0].y.reg == b && p[3].x.reg == b && literal(p[3].y, -2) &&
183 p[5].x.reg == c && literal(p[5].y, -5) && p[0].x.reg != a &&
184 p[0].x.reg != b && p[0].x.reg != c) {
185 int64_t x = value(p[0].x, r), y = r[c];
186 if (x > 0 && y > 0) {
187 aoc_assert(x <= REGCAP / y, "register exceeds cap");
188 add(&r[a], x * y);
189 r[b] = r[c] = 0;
190 return 6;
191 }
192 }
193 }
194 if (pc + 2 < nins && p[2].op == JNZ && literal(p[2].y, -2)) {
195 struct ins *inc = p, *dec = p + 1;
196 if (inc->op == DEC && dec->op == INC) {
197 inc = p + 1;
198 dec = p;
199 }
200 int a = inc->x.reg, b = dec->x.reg;
201 if (inc->op == INC && dec->op == DEC && a >= 0 && b >= 0 && a != b &&
202 p[2].x.reg == b && r[b] > 0) {
203 add(&r[a], r[b]);
204 r[b] = 0;
205 return 3;
206 }
207 }
208 return 0;
209}
210
211static int64_t execute(int64_t pc, int64_t r[4]) {
212 int skip = optimize((int)pc, r);
213 if (skip) {
214 return pc + skip;
215 }
216 struct ins in = code[pc];
217 int64_t x = value(in.x, r);
218 switch (in.op) {
219 case CPY:
220 if (in.y.reg >= 0) {
221 r[in.y.reg] = x;
222 }
223 break;
224 case INC:
225 if (in.x.reg >= 0) {
226 add(&r[in.x.reg], 1);
227 }
228 break;
229 case DEC:
230 if (in.x.reg >= 0) {
231 add(&r[in.x.reg], -1);
232 }
233 break;
234 case JNZ:
235 if (x) {
236 return pc + value(in.y, r);
237 }
238 break;
239 case TGL: {
240 int64_t q = pc + x;
241 if (q >= 0 && q < nins) {
242 uint8_t op = code[q].op;
243 code[q].op = op == CPY || op == JNZ ? (op == JNZ ? CPY : JNZ)
244 : (op == INC ? DEC : INC);
245 }
246 break;
247 }
248 default:
249 aoc_assert(0, "unexpected output instruction");
250 }
251 return pc + 1;
252}
253
254static slice solve(slice in, int64_t a) {
255 load(in);
256 for (int k = 0; k < nins; k++) {
257 aoc_assert(program[k].op != OUT, "bad instruction");
258 }
259 memcpy(code, program, (size_t)nins * sizeof code[0]);
260 int64_t r[4] = {a, 0, 0, 0}, pc = 0;
261 int steps = 0;
262 while (pc >= 0 && pc < nins) {
263 aoc_assert(++steps <= STEPMAX, "program exceeds step budget");
264 pc = execute(pc, r);
265 }
266 return slice_from_i64(r[0]);
267}
268
269slice part1(slice in) {
270 return solve(in, 7);
271}
272
273slice part2(slice in) {
274 return solve(in, 12);
275}
276
277static slice estimate(slice in) {
278 load(in);
279 for (int k = 0; k < nins; k++) {
280 aoc_assert(program[k].op != OUT, "bad instruction");
281 }
282 return slice_from_i64(nins);
283}
284
285const struct aoc_method aoc_methods[] = {
286 {"estimate", estimate},
287 {0, 0},
288};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
We already have an assembunny interpreter. A promising start—until the new instruction edits the program while it runs. Keep a mutable copy of the code and take tgl literally: toggle by argument count, retain operands, ignore out-of-range targets, and skip invalid writes such as copying into a literal. Even an instruction can toggle itself. Finish its current action first; its new meaning waits for the next visit. The little example is worth tracing before trusting this surprisingly slippery extension.
The public example ends with a = 3 and is a compact way to check those rules. In particular, its toggled copy becomes a jump whose offset is held in a register. Assuming all jump offsets are literals would miss an instruction the story explicitly creates. A fresh run must also start from the original program, not from the mutations left by the previous run.
Twenty-six instructions and a = 7 take 61,471 literal steps. The interpreter works, the answer appears, and the safe complains. We recount the eggs: twelve. This run needs 3,501,378,446 instructions, as we can calculate by summing its loop iterations. Five overlooked eggs have turned a quick solve into an overheating computer. The story even nudges us toward the cause: all it knows is how to add one, and bunnies are supposed to multiply.
Watch one inner inc/dec/jnz loop: it adds a counter into an accumulator. Watch the surrounding loop: it reloads the counter and performs that addition again. Multiplication, done the hard way. Step back once more and the local program multiplies 12 by 11, then 10, then 9, down to 2. There is the factorial, followed by 90 × 90. The earlier run began at 7, and 12! is 95,040 times 7!. The waiting now makes sense, and so does the way around it.
Recognizing the arithmetic gives two ways forward: derive the result of this specific program, or teach the interpreter to execute the repeated blocks in one step. The implementation does the latter. A multiplication block adds source × outer-counter to the destination and leaves both consumed counters at zero. Those final counter values matter because the following code may inspect them. A shortcut must reproduce the whole relevant state, not only the register eventually printed.
One last discomfort: we just taught the interpreter to recognize a loop in a program that can rewrite its own loops. Recognizing it once at load time is not enough. Inspect the current instructions when we reach the block, check the exact jumps and distinct registers, and require positive counters with an unchanged source. If execution jumps into the middle, interpret from there. The shortcut earns its validity at the moment it is used, even while tgl keeps changing the program.
The implementation accepts at most 256 instructions, literal magnitudes through one billion, registers within ±one trillion, and one million executed steps after recognized blocks are collapsed. Input text is capped at 65,536 characters. It starts a at 7 or 12 as the story specifies. The estimate method reports program length, which is useful for inventory but cannot predict execution cost; the contrast between 26 instructions and billions of executed steps is the puzzle's central warning.
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.