2019 / Day 25
Cryostasis
Read the original puzzle on adventofcode.com ↗
The solution
solution.c
1#include "intcode.h"
2
3/* The local adventure has a 4798-cell program, touches address 5018, and
4 * contains 19 rooms with eight safe items. The five hazardous item names are
5 * visible during exploration and are excluded explicitly. ROOMS = 32, ITEMS =
6 * 8, MEM = 8192, and STEPS = 2097152 bound that observed ship. Explore
7 * reversible exits, collect the safe items, and locate the pressure gate from
8 * its rejection message. At the checkpoint, positive item weights let a
9 * too-light subset rule out its subsets and a too-heavy subset rule out its
10 * supersets. Choose trials that prune both directions; the local ship solves in
11 * 1146993 instructions and 618504 subset comparisons. The password is read from
12 * the successful computer response. Day 25 has no computational part two. */
13
14enum {
15 MEM = 8192,
16 STEPS = 2097152,
17 ROOMS = 32,
18 ITEMS = 8,
19 NAME = 64,
20 RESPONSE = 8192,
21 SUBSETS = 1 << ITEMS,
22 WORK = 4194304
23};
24
25static int64_t memory[MEM];
26static Ic machine;
27static char response[RESPONSE + 1], items[ITEMS][NAME];
28
29typedef struct {
30 char name[NAME];
31 int exits, edge[4], visited;
32} Room;
33
34static Room rooms[ROOMS];
35static int nr, ni, gate, gate_dir, work;
36static int64_t password;
37static const char *directions[4] = {"north", "south", "west", "east"};
38static const int reverse[4] = {1, 0, 3, 2};
39
40static const char *find(const char *s, const char *needle) {
41 size_t n = strlen(needle), len = strlen(s);
42 for (size_t i = 0; i + n <= len; i++) {
43 if (!memcmp(s + i, needle, n)) {
44 return s + i;
45 }
46 }
47 return NULL;
48}
49
50static int equal(const char *a, const char *b) {
51 size_t n = strlen(a);
52 return n == strlen(b) && !memcmp(a, b, n);
53}
54
55static void copy(char *dst, const char *s, size_t n) {
56 aoc_assert(n && n < NAME, "adventure name cap");
57 memcpy(dst, s, n);
58 dst[n] = 0;
59}
60
61static void read_response(void) {
62 size_t n = 0;
63 int64_t out;
64 int status;
65 while ((status = ic_step(&machine, &out)) == IC_OUT) {
66 aoc_assert(out >= 0 && out < 128 && n < RESPONSE,
67 "adventure response cap");
68 response[n++] = (char)out;
69 }
70 aoc_assert(status == IC_NEED || status == IC_HALT,
71 "adventure instruction cap");
72 response[n] = 0;
73 const char *p = find(response, "typing ");
74 if (p) {
75 p += 7;
76 const char *start = p;
77 while (*p >= '0' && *p <= '9') {
78 p++;
79 }
80 int64_t value;
81 aoc_assert(
82 p > start &&
83 slice_to_i64((slice){(uint8_t *)start, (size_t)(p - start)},
84 &value) &&
85 find(p, "keypad"),
86 "bad airlock password");
87 password = value;
88 }
89}
90
91static void command(const char *verb, const char *item) {
92 for (size_t i = 0; verb[i]; i++) {
93 ic_push(&machine, (uint8_t)verb[i]);
94 }
95 if (item) {
96 ic_push(&machine, ' ');
97 for (size_t i = 0; item[i]; i++) {
98 ic_push(&machine, (uint8_t)item[i]);
99 }
100 }
101 ic_push(&machine, '\n');
102 read_response();
103}
104
105static inline __attribute__((always_inline)) int
106identify_room_direction(const char *doors, const char *e, int d) {
107 for (int i = 0; i < 4; i++) {
108 if ((size_t)(e - doors) == strlen(directions[i]) &&
109 !memcmp(doors, directions[i], (size_t)(e - doors))) {
110 d = i;
111 }
112 }
113
114 return d;
115}
116
117static int room(void) {
118 const char *p = response, *last = NULL;
119 while ((p = find(p, "== "))) {
120 last = p;
121 p += 3;
122 }
123 aoc_assert(last, "missing room description");
124 last += 3;
125 const char *end = find(last, " ==");
126 aoc_assert(end, "bad room description");
127 char name[NAME];
128 copy(name, last, (size_t)(end - last));
129 int id = -1;
130 for (int i = 0; i < nr; i++) {
131 if (equal(rooms[i].name, name)) {
132 id = i;
133 break;
134 }
135 }
136 if (id < 0) {
137 aoc_assert(nr < ROOMS, "adventure room cap");
138 id = nr++;
139 memset(&rooms[id], 0, sizeof rooms[id]);
140 copy(rooms[id].name, name, strlen(name));
141 for (int d = 0; d < 4; d++) {
142 rooms[id].edge[d] = -1;
143 }
144 }
145 const char *doors = find(end, "Doors here lead:\n");
146 aoc_assert(doors, "missing room exits");
147 doors += 17;
148 int exits = 0;
149 while (doors[0] == '-' && doors[1] == ' ') {
150 doors += 2;
151 const char *e = find(doors, "\n");
152 aoc_assert(e, "bad room exit");
153 int d = -1;
154 d = identify_room_direction(doors, e, d);
155 aoc_assert(d >= 0 && !(exits & (1 << d)), "bad room exit");
156 exits |= 1 << d;
157 doors = e + 1;
158 }
159 if (rooms[id].visited) {
160 aoc_assert(rooms[id].exits == exits, "room exits changed");
161 }
162 rooms[id].exits = exits;
163 return id;
164}
165
166static int hazardous(const char *name) {
167 static const char *bad[5] = {"infinite loop", "giant electromagnet",
168 "escape pod", "molten lava", "photons"};
169 for (int i = 0; i < 5; i++) {
170 if (equal(name, bad[i])) {
171 return 1;
172 }
173 }
174 return 0;
175}
176
177static inline __attribute__((always_inline)) void
178check_unique_loot(char loot[ITEMS][NAME], int i) {
179 for (int j = 0; j < ni; j++) {
180 aoc_assert(!equal(items[j], loot[i]), "duplicate adventure item");
181 }
182}
183
184static void explore(int id) {
185 rooms[id].visited =
186 1; /* Copy the item list before commands replace the response buffer. */
187 char loot[ITEMS][NAME];
188 int count = 0;
189 const char *p = find(response, "Items here:\n");
190 if (p) {
191 p += 12;
192 while (p[0] == '-' && p[1] == ' ') {
193 p += 2;
194 const char *end = find(p, "\n");
195 aoc_assert(end && count < ITEMS, "room item cap");
196 copy(loot[count++], p, (size_t)(end - p));
197 p = end + 1;
198 }
199 }
200 for (int i = 0; i < count; i++) {
201 if (hazardous(loot[i])) {
202 continue;
203 }
204 aoc_assert(ni < ITEMS, "safe item cap");
205 check_unique_loot(loot, i);
206 copy(items[ni], loot[i], strlen(loot[i]));
207 command("take", items[ni++]);
208 aoc_assert(find(response, "You take the "), "could not take item");
209 }
210 for (int d = 0; d < 4; d++) {
211 if (!(rooms[id].exits & (1 << d)) || rooms[id].edge[d] >= 0) {
212 continue;
213 }
214 command(directions[d], NULL);
215 if (password >= 0) {
216 return;
217 }
218 int next = room();
219 if (find(response, "Alert!")) {
220 aoc_assert(equal(rooms[id].name, "Security Checkpoint") &&
221 next == id &&
222 (gate < 0 || (gate == id && gate_dir == d)),
223 "unsupported pressure gate");
224 gate = id;
225 gate_dir = d;
226 continue;
227 }
228 aoc_assert(next != id, "movement did not change room");
229 rooms[id].edge[d] = next;
230 aoc_assert(rooms[next].edge[reverse[d]] < 0 ||
231 rooms[next].edge[reverse[d]] == id,
232 "inconsistent room graph");
233 rooms[next].edge[reverse[d]] = id;
234 if (!rooms[next].visited) {
235 explore(next);
236 if (password >= 0) {
237 return;
238 }
239 }
240 command(directions[reverse[d]], NULL);
241 aoc_assert(room() == id, "adventure failed to backtrack");
242 }
243}
244
245static inline __attribute__((always_inline)) int
246visit_checkpoint_neighbors(int previous[ROOMS], int via[ROOMS],
247 int queue[ROOMS], int tail, int id) {
248 for (int d = 0; d < 4; d++) {
249 int next = rooms[id].edge[d];
250 if (next >= 0 && previous[next] < 0) {
251 previous[next] = id;
252 via[next] = d;
253 queue[tail++] = next;
254 }
255 }
256
257 return tail;
258}
259
260static void checkpoint(void) {
261 int previous[ROOMS], via[ROOMS], queue[ROOMS], path[ROOMS];
262 for (int i = 0; i < nr; i++) {
263 previous[i] = -1;
264 }
265 int head = 0, tail = 0;
266 queue[tail++] = 0;
267 previous[0] = 0;
268 while (head < tail) {
269 int id = queue[head++];
270 tail = visit_checkpoint_neighbors(previous, via, queue, tail, id);
271 }
272 aoc_assert(previous[gate] >= 0, "checkpoint disconnected");
273 int n = 0;
274 for (int id = gate; id != 0; id = previous[id]) {
275 path[n++] = via[id];
276 }
277 while (n) {
278 command(directions[path[--n]], NULL);
279 room();
280 }
281 aoc_assert(room() == gate, "checkpoint navigation failed");
282}
283
284static inline __attribute__((always_inline)) void
285count_weight_partitions(uint8_t possible[SUBSETS], int limit, int a,
286 int *below_ref, int *above_ref) {
287 for (int b = 0; b < limit; b++) {
288 if (!possible[b]) {
289 continue;
290 }
291 aoc_assert(++work <= WORK, "adventure subset work cap");
292 (*below_ref) += (b & a) == b;
293 (*above_ref) += (b & a) == a;
294 }
295}
296
297static inline __attribute__((always_inline)) void
298choose_weight_candidate(uint8_t possible[SUBSETS], int limit,
299 int *candidate_ref, int *best_ref) {
300 for (int a = 0; a < limit; a++) {
301 if (!possible[a]) {
302 continue;
303 }
304 int below = 0, above = 0;
305 count_weight_partitions(possible, limit, a, &below, &above);
306 int score = below < above ? below : above;
307 if (score > (*best_ref)) {
308 (*best_ref) = score;
309 (*candidate_ref) = a;
310 }
311 }
312}
313
314static inline __attribute__((always_inline)) int
315equip_weight_candidate(int current, int candidate) {
316 for (int i = 0; i < ni; i++) {
317 if ((current ^ candidate) & (1 << i)) {
318 command(candidate & (1 << i) ? "take" : "drop", items[i]);
319 aoc_assert(find(response, candidate & (1 << i) ? "You take the "
320 : "You drop the "),
321 "inventory change failed");
322 }
323 }
324
325 return candidate;
326}
327
328static inline __attribute__((always_inline)) void
329eliminate_weight_candidates(uint8_t possible[SUBSETS], int limit, int current,
330 int light, int heavy) {
331 for (int b = 0; b < limit; b++) {
332 if ((light && (b & current) == b) ||
333 (heavy && (b & current) == current)) {
334 possible[b] = 0;
335 }
336 }
337}
338
339static void weigh(void) {
340 uint8_t possible[SUBSETS];
341 int limit = 1 << ni;
342 memset(possible, 1, (size_t)limit);
343 int current = limit - 1;
344 for (int attempt = 0; attempt < limit; attempt++) {
345 int candidate = -1, best = -1;
346 choose_weight_candidate(possible, limit, &candidate, &best);
347 aoc_assert(candidate >= 0, "no valid item subset");
348 candidate = equip_weight_candidate(current, candidate);
349 current = candidate;
350 command(directions[gate_dir], NULL);
351 if (password >= 0) {
352 return;
353 }
354 aoc_assert(find(response, "Alert!") && room() == gate,
355 "pressure gate did not return");
356 int light = find(response, "heavier") != NULL,
357 heavy = find(response, "lighter") != NULL;
358 aoc_assert(light != heavy, "unknown pressure feedback");
359 eliminate_weight_candidates(possible, limit, current, light, heavy);
360 }
361 aoc_assert(0, "adventure trial cap");
362}
363
364slice part1(slice in) {
365 ic_load(&machine, memory, MEM, in);
366 machine.budgeted = 1;
367 machine.left = STEPS;
368 nr = ni = work = 0;
369 gate = gate_dir = -1;
370 password = -1;
371 read_response();
372 if (password < 0) {
373 int start = room();
374 aoc_assert(start == 0, "bad starting room");
375 explore(start);
376 }
377 if (password < 0) {
378 aoc_assert(gate >= 0, "missing pressure gate");
379 checkpoint();
380 weigh();
381 }
382 return slice_from_i64(password);
383}
384
385slice part2(slice in) {
386 (void)in;
387 return empty_slice;
388}
389
390const 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#endifintcode.h
1#ifndef INTCODE_H
2#define INTCODE_H
3
4#include "aoc.h"
5
6/* 2019's Intcode computer. A solution is otherwise complete by
7 * itself, and the same small parser is written again in every day.
8 * This machine is the exception, on purpose: days 2, 5, 7, 9, 11,
9 * 13, 15, 17, 19, 21, 23, and 25 run one computer, so it lives here
10 * once, next to aoc.h, instead of being copied into each of them.
11 *
12 * The caller owns the memory table and keeps large tables in static storage.
13 * One cell is an int64_t, and a table large enough for a program
14 * does not fit on the 64KiB stack. IC_IN is the queued-input cap.
15 * An address outside the table, a mode other than 0, 1, or 2, or an
16 * unknown opcode stops the run. Cells and arithmetic are signed 64-bit;
17 * overflow is rejected rather than wrapped. Programs are comma-separated
18 * decimal integers, with optional spaces, tabs, CR, and LF around each cell.
19 *
20 * ic_step runs until the next output, until an input is required
21 * and the queue is empty, or until opcode 99. The caller resumes
22 * with another ic_step. budgeted is 0 unless the caller sets it.
23 * When it is set, left is the number of instructions still allowed.
24 * Only executed instructions (including 99) consume it; waiting for input
25 * does not. The instruction that would pass the budget is not consumed,
26 * and ic_step returns IC_BUDGET. ic_reset clears both. With budgeting off,
27 * the enclosing runtime's execution limit still bounds a looping program.
28 * ic_reset restores a program image and clears only the cells the
29 * previous run wrote past the program. Save the image before running or
30 * poking the machine. The image and each cloned machine need distinct
31 * caller-owned arrays; clone copies the entire state, including queued input.
32 * Use ic_poke for external writes so reset knows which cells to clear.
33 */
34
35enum {
36 IC_IN = 256,
37 IC_HALT = 0,
38 IC_OUT = 1,
39 IC_NEED = 2,
40 IC_BUDGET = 3,
41};
42
43typedef struct {
44 int64_t *mem;
45 int64_t base;
46 int64_t inq[IC_IN];
47 size_t cap;
48 size_t n;
49 size_t ip;
50 size_t hi;
51 size_t in_i;
52 size_t in_n;
53 int32_t left;
54 int budgeted;
55 int halted;
56} Ic;
57
58static int64_t ic_add(int64_t a, int64_t b) {
59 if (b >= 0) {
60 aoc_assert(a <= INT64_MAX - b, "intcode overflow");
61 } else {
62 aoc_assert(a >= INT64_MIN - b, "intcode overflow");
63 }
64 return a + b;
65}
66
67static int64_t ic_mul(int64_t a, int64_t b) {
68 uint64_t ua;
69 uint64_t ub;
70 uint64_t r;
71 uint64_t limit;
72 int neg;
73 neg = (a < 0) != (b < 0);
74 ua = a < 0 ? (uint64_t)(-(a + 1)) + 1u : (uint64_t)a;
75 ub = b < 0 ? (uint64_t)(-(b + 1)) + 1u : (uint64_t)b;
76 limit = (uint64_t)INT64_MAX + (uint64_t)neg;
77 aoc_assert(ub == 0 || ua <= limit / ub, "intcode overflow");
78 r = ua * ub;
79 if (neg && r == (uint64_t)INT64_MAX + 1u) {
80 return INT64_MIN;
81 }
82 return neg ? -(int64_t)r : (int64_t)r;
83}
84
85static int ic_space(uint8_t c) {
86 return c == ' ' || c == '\t' || c == '\r' || c == '\n';
87}
88
89static void ic_load(Ic *m, int64_t *mem, size_t cap, slice src) {
90 size_t i = 0;
91 size_t n = 0;
92 aoc_assert(m && mem && cap > 0 && cap <= SIZE_MAX / sizeof *mem,
93 "intcode memory");
94 aoc_assert(src.p || src.l == 0, "intcode program");
95 memset(mem, 0, cap * sizeof *mem);
96 memset(m, 0, sizeof *m);
97 m->mem = mem;
98 m->cap = cap;
99 while (i < src.l && ic_space(src.p[i])) {
100 i++;
101 }
102 aoc_assert(i < src.l, "empty program");
103 while (i < src.l) {
104 size_t start = i;
105 int64_t v;
106 aoc_assert(n < cap, "program exceeds cap");
107 if (src.p[i] == '-') {
108 i++;
109 }
110 while (i < src.l && src.p[i] >= '0' && src.p[i] <= '9') {
111 i++;
112 }
113 aoc_assert(i > start && !(i == start + 1 && src.p[start] == '-'),
114 "expected integer");
115 aoc_assert(slice_to_i64((slice){src.p + start, i - start}, &v),
116 "integer exceeds cap");
117 mem[n++] = v;
118 while (i < src.l && ic_space(src.p[i])) {
119 i++;
120 }
121 if (i == src.l) {
122 break;
123 }
124 aoc_assert(src.p[i] == ',', "expected comma");
125 i++;
126 while (i < src.l && ic_space(src.p[i])) {
127 i++;
128 }
129 aoc_assert(i < src.l, "trailing comma");
130 }
131 aoc_assert(n > 0, "empty program");
132 m->n = n;
133 m->hi = n;
134}
135
136static void ic_image(const Ic *m, int64_t *image) {
137 memcpy(image, m->mem, m->n * sizeof *image);
138}
139
140static void ic_reset(Ic *m, const int64_t *image) {
141 memcpy(m->mem, image, m->n * sizeof *image);
142 if (m->hi > m->n) {
143 memset(m->mem + m->n, 0, (m->hi - m->n) * sizeof *m->mem);
144 }
145 m->base = 0;
146 m->ip = 0;
147 m->in_i = 0;
148 m->in_n = 0;
149 m->left = 0;
150 m->budgeted = 0;
151 m->halted = 0;
152 m->hi = m->n;
153}
154
155static void ic_clone(Ic *dst, int64_t *mem, const Ic *src) {
156 aoc_assert(dst && mem && dst != src && mem != src->mem,
157 "intcode clone memory");
158 memcpy(mem, src->mem, src->cap * sizeof *mem);
159 *dst = *src;
160 dst->mem = mem;
161}
162
163static void ic_poke(Ic *m, int64_t addr, int64_t v) {
164 aoc_assert(addr >= 0 && (uint64_t)addr < m->cap, "intcode address");
165 m->mem[addr] = v;
166 if ((size_t)addr + 1 > m->hi) {
167 m->hi = (size_t)addr + 1;
168 }
169}
170
171static int64_t ic_peek(const Ic *m, int64_t addr) {
172 aoc_assert(addr >= 0 && (uint64_t)addr < m->cap, "intcode address");
173 return m->mem[addr];
174}
175
176static void ic_push(Ic *m, int64_t v) {
177 if (m->in_i == m->in_n) {
178 m->in_i = 0;
179 m->in_n = 0;
180 } else if (m->in_n == IC_IN && m->in_i > 0) {
181 m->in_n -= m->in_i;
182 memmove(m->inq, m->inq + m->in_i, m->in_n * sizeof *m->inq);
183 m->in_i = 0;
184 }
185 aoc_assert(m->in_n < IC_IN, "intcode input");
186 m->inq[m->in_n++] = v;
187}
188
189static size_t ic_index(const Ic *m, int mode, size_t at) {
190 int64_t a;
191 aoc_assert(at < m->cap, "intcode address");
192 aoc_assert(mode == 0 || mode == 2, "bad mode");
193 a = m->mem[at];
194 if (mode == 2) {
195 a = ic_add(a, m->base);
196 }
197 aoc_assert(a >= 0 && (uint64_t)a < m->cap, "intcode address");
198 return (size_t)a;
199}
200
201static int64_t ic_read(const Ic *m, int mode, size_t at) {
202 size_t a;
203 aoc_assert(mode == 0 || mode == 1 || mode == 2, "bad mode");
204 if (mode == 1) {
205 aoc_assert(at < m->cap, "intcode address");
206 return m->mem[at];
207 }
208 a = ic_index(m, mode, at);
209 return m->mem[a];
210}
211
212static void ic_write(Ic *m, int mode, size_t at, int64_t v) {
213 size_t a = ic_index(m, mode, at);
214 m->mem[a] = v;
215 if (a + 1 > m->hi) {
216 m->hi = a + 1;
217 }
218}
219
220static int ic_step(Ic *m, int64_t *out) {
221 if (m->halted) {
222 return IC_HALT;
223 }
224 for (;;) {
225 int64_t ins;
226 int op;
227 int mode;
228 int m0;
229 int m1;
230 int m2;
231 size_t width;
232 if (m->budgeted && m->left <= 0) {
233 return IC_BUDGET;
234 }
235 aoc_assert(m->ip < m->cap, "intcode address");
236 ins = m->mem[m->ip];
237 aoc_assert(ins >= 0, "bad opcode");
238 aoc_assert(ins < 100000, "bad mode");
239 op = (int)(ins % 100);
240 mode = (int)(ins / 100);
241 m0 = mode % 10;
242 m1 = (mode / 10) % 10;
243 m2 = mode / 100;
244 aoc_assert(m0 <= 2 && m1 <= 2 && m2 <= 2, "bad mode");
245 switch (op) {
246 case 99:
247 width = 1;
248 break;
249 case 3:
250 case 4:
251 case 9:
252 width = 2;
253 break;
254 case 5:
255 case 6:
256 width = 3;
257 break;
258 case 1:
259 case 2:
260 case 7:
261 case 8:
262 width = 4;
263 break;
264 default:
265 aoc_assert(0, "bad opcode");
266 }
267 aoc_assert(width <= m->cap - m->ip, "intcode address");
268 if (op == 3 && m->in_i >= m->in_n) {
269 /* Validate a blocked input instruction before yielding. */
270 (void)ic_index(m, m0, m->ip + 1);
271 return IC_NEED;
272 }
273 if (m->budgeted) {
274 m->left--;
275 }
276 if (op == 99) {
277 m->halted = 1;
278 return IC_HALT;
279 }
280 if (op == 3) {
281 ic_write(m, m0, m->ip + 1, m->inq[m->in_i++]);
282 m->ip += 2;
283 continue;
284 }
285 if (op == 4) {
286 aoc_assert(out, "intcode output");
287 *out = ic_read(m, m0, m->ip + 1);
288 m->ip += 2;
289 return IC_OUT;
290 }
291 if (op == 9) {
292 m->base = ic_add(m->base, ic_read(m, m0, m->ip + 1));
293 m->ip += 2;
294 continue;
295 }
296 if (op == 5 || op == 6) {
297 int64_t cond = ic_read(m, m0, m->ip + 1);
298 int64_t dest = ic_read(m, m1, m->ip + 2);
299 int take = op == 5 ? cond != 0 : cond == 0;
300 if (take) {
301 aoc_assert(dest >= 0 && (uint64_t)dest < m->cap,
302 "intcode address");
303 m->ip = (size_t)dest;
304 } else {
305 m->ip += 3;
306 }
307 continue;
308 }
309 if (op == 1 || op == 2 || op == 7 || op == 8) {
310 int64_t x = ic_read(m, m0, m->ip + 1);
311 int64_t y = ic_read(m, m1, m->ip + 2);
312 int64_t r = 0;
313 if (op == 1) {
314 r = ic_add(x, y);
315 } else if (op == 2) {
316 r = ic_mul(x, y);
317 } else if (op == 7) {
318 r = x < y;
319 } else {
320 r = x == y;
321 }
322 ic_write(m, m2, m->ip + 3, r);
323 m->ip += 4;
324 continue;
325 }
326 aoc_assert(0, "bad opcode");
327 }
328}
329
330#endifThe aha moment
Santa's ship is freezing, one life sign remains, and our input is another Intcode program. This time it is a text adventure. Before looking for an algorithm, run it and read what it says. The room descriptions, exits, items, and rejection messages are the observations from which the problem's structure emerges.
The local program has 4,798 cells, but its addressable world is much smaller than the program listing suggests: nineteen rooms are mapped before passing the pressure floor, and eight useful items can be collected. A person can explore this ship with a notebook and a small interactive terminal. Automating a general adventure-game solver would be a much larger project than solving this adventure.
For the implementation, room names identify nodes in a graph and compass directions identify edges. Explore an unvisited exit, record where it leads, and use the opposite direction to return after finishing that branch. Keep the computer alive throughout. As with the repair droid, exploration and later navigation are separate tasks; once the graph is known, a short breadth-first search supplies a route back to the checkpoint.
Taking everything is an appealing plan until an item ends the expedition or prevents further movement. The implementation explicitly excludes five known hazards: infinite loop, giant electromagnet, escape pod, molten lava, and photons. Their names are not a general item-safety classifier. This is knowledge of the observed adventure encoded as a small exclusion list. When discovering an unfamiliar item interactively, a saved machine state and a bounded experiment would let us investigate without losing all earlier exploration.
The pressure floor changes the final task into an inventory problem. Carrying all useful items is not necessarily right, and carrying the right number of items is not enough because their weights differ. Eight items give only 2 to the power eight, or 256, possible subsets. Exhaustive trials are therefore a legitimate baseline. We do not need to infer each hidden weight or solve a large numerical optimization problem.
Still, each trial means issuing commands and running the adventure. The checkpoint's rejection contains information we can use. Under the positive-item-weight assumption, a subset that is too light rules out every subset of itself: removing items cannot make it heavy enough. A subset that is too heavy rules out every superset: adding items cannot make it lighter.
Read the sentence carefully before interpreting that feedback. A message saying the expected droids are heavier means our detected weight is too light. Reversing that comparison would discard the useful half of the evidence. After a rejection, the program returns us to the checkpoint, ready for another experiment.
There is no ordinary binary search over subset numbers. Bit-mask order has no relationship to weight, and two incomparable subsets may contain very different items. Instead, retain the still-possible subsets. For each proposed trial, count how many surviving subsets would be eliminated by a too-light result and how many surviving supersets by a too-heavy result. Prefer a trial that makes the smaller of those two eliminations as large as possible.
This is a heuristic for choosing informative experiments, with exact pruning once the feedback arrives. It need not achieve the fewest trials. On the local adventure, the search succeeds after 51 checkpoint trials, rather than needing to try all 256 subsets, and spends 618,504 inexpensive subset comparisons selecting them. Change only items whose inclusion differs from the previous trial; leave the rest of the inventory alone.
The complete local solve uses 284 commands and 1,146,993 Intcode instructions, reaching memory address 5,018. The implementation allows 32 rooms, eight safe items, names through 63 characters, responses through 8,192 characters, 8,192 memory cells, 2,097,152 instructions, and 4,194,304 subset comparisons. It checks reversible navigation and recognizable checkpoint feedback, and reads the password from the successful response rather than embedding the answer. There is no computational part two; that endpoint returns an empty result.
The year's final breakthrough comes from treating the program as something to converse with. Explore, keep notes, make a hypothesis, try an inventory, and let a failed attempt reduce the uncertainty. The computer we assembled one instruction at a time has become the instrument that lets us find Santa.
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.