2024 / Day 15
Warehouse Woes
Read the original puzzle on adventofcode.com ↗
The solution
solution.c
1#include "aoc.h"
2
3/* The local input is 22571 bytes, 71 lines, longest line 1000. The warehouse is
4 * 50 by 50 with 603 boxes and 20000 moves. WIDTH = 256 after widening, HEIGHT =
5 * 128 and MOVES = 65536 bound it. For each push, collect dependent boxes by
6 * their left cell; refuse the move if any destination is a wall, otherwise
7 * clear all old boxes before moving them together. WORK = 2000000 examined
8 * boxes bounds push work. */
9
10static slice line(slice s, size_t *p) {
11 size_t b = *p;
12 while (*p < s.l && s.p[*p] != '\n') {
13 (*p)++;
14 }
15 size_t e = *p;
16 if (*p < s.l) {
17 (*p)++;
18 }
19 if (e > b && s.p[e - 1] == '\r') {
20 e--;
21 }
22 return (slice){s.p + b, e - b};
23}
24
25enum {
26 WIDTH = 256,
27 HEIGHT = 128,
28 CELLS = WIDTH * HEIGHT,
29 MOVES = 65536,
30 WORK = 2000000
31};
32
33static uint8_t map[HEIGHT][WIDTH];
34static uint32_t seen[HEIGHT][WIDTH];
35static int32_t boxes[CELLS];
36
37static inline __attribute__((always_inline)) void
38read_warehouse_row(int32_t h, int32_t *rx_ref, int32_t *ry_ref, int32_t wide,
39 slice l) {
40 for (size_t x = 0; x < l.l; x++) {
41 uint8_t c = l.p[x];
42 aoc_assert(c == '#' || c == '.' || c == 'O' || c == '@',
43 "bad warehouse cell");
44 int32_t xx = x * (wide + 1);
45 if (c == '@') {
46 aoc_assert((*rx_ref) < 0, "multiple warehouse robots");
47 (*rx_ref) = xx;
48 (*ry_ref) = h;
49 c = '.';
50 }
51 map[h][xx] = c == 'O' && wide ? '[' : c;
52 if (wide) {
53 map[h][xx + 1] = c == 'O' ? ']' : c;
54 }
55 }
56}
57
58static inline __attribute__((always_inline)) void
59check_pushed_box_cells(int32_t w, int32_t wide, uint32_t stamp, int32_t dx,
60 int32_t dy, int32_t *count_ref, int32_t *blocked_ref,
61 int32_t x, int32_t y) {
62 for (int32_t k = 0; k <= wide; k++) {
63 int32_t xx = x + dx + k, yy = y + dy;
64 uint8_t dest = map[yy][xx];
65 if (dest == '#') {
66 (*blocked_ref) = 1;
67 break;
68 }
69 if (dest != '.') {
70 int32_t bx = xx - (dest == ']');
71 if (bx == x && yy == y) {
72 continue;
73 }
74 if (seen[yy][bx] != stamp) {
75 seen[yy][bx] = stamp;
76 aoc_assert((*count_ref) < CELLS,
77 "push exceeds warehouse cell bound");
78 boxes[(*count_ref)++] = yy * w + bx;
79 }
80 }
81 }
82}
83
84static inline __attribute__((always_inline)) void
85collect_pushed_boxes(int32_t w, int32_t wide, int32_t *work_ref, uint32_t stamp,
86 int32_t dx, int32_t dy, int32_t *count_ref,
87 int32_t *blocked_ref) {
88 for (int32_t q = 0; q < (*count_ref) && !(*blocked_ref); q++) {
89 aoc_assert(++(*work_ref) <= WORK,
90 "warehouse pushes exceed 2000000 examined boxes");
91 int32_t x = boxes[q] % w, y = boxes[q] / w;
92 check_pushed_box_cells(w, wide, stamp, dx, dy, count_ref, blocked_ref,
93 x, y);
94 }
95}
96
97static inline __attribute__((always_inline)) void
98clear_pushed_boxes(int32_t w, int32_t wide, int32_t count) {
99 for (int32_t q = 0; q < count; q++) {
100 int32_t x = boxes[q] % w, y = boxes[q] / w;
101 map[y][x] = '.';
102 if (wide) {
103 map[y][x + 1] = '.';
104 }
105 }
106}
107
108static inline __attribute__((always_inline)) void
109place_pushed_boxes(int32_t w, int32_t wide, int32_t dx, int32_t dy,
110 int32_t count) {
111 for (int32_t q = 0; q < count; q++) {
112 int32_t x = boxes[q] % w + dx, y = boxes[q] / w + dy;
113 map[y][x] = wide ? '[' : 'O';
114 if (wide) {
115 map[y][x + 1] = ']';
116 }
117 }
118}
119
120static slice solve(slice s, int32_t part) {
121 size_t p = 0;
122 int32_t w = 0, h = 0, rx = -1, ry = -1, wide = part == 2, work = 0;
123 memset(seen, 0, sizeof seen);
124 while (p < s.l) {
125 slice l = line(s, &p);
126 if (!l.l) {
127 break;
128 }
129 aoc_assert(h < HEIGHT && l.l && l.l * (wide + 1) <= WIDTH,
130 "warehouse exceeds 256 by 128 after widening");
131 int32_t width = l.l * (wide + 1);
132 if (!h) {
133 w = width;
134 }
135 aoc_assert(width == w, "ragged warehouse");
136 read_warehouse_row(h, &rx, &ry, wide, l);
137 h++;
138 }
139 aoc_assert(rx >= 0 && h >= 3 && w >= 3,
140 "missing warehouse robot or too small");
141 for (int32_t x = 0; x < w; x++) {
142 aoc_assert(map[0][x] == '#' && map[h - 1][x] == '#',
143 "warehouse boundary must be walls");
144 }
145 for (int32_t y = 0; y < h; y++) {
146 aoc_assert(map[y][0] == '#' && map[y][w - 1] == '#',
147 "warehouse boundary must be walls");
148 }
149 int32_t moves = 0;
150 uint32_t stamp = 0;
151 while (p < s.l) {
152 uint8_t c = s.p[p++];
153 if (c == '\n' || c == '\r') {
154 continue;
155 }
156 aoc_assert(++moves <= MOVES, "warehouse exceeds 65536 moves");
157 int32_t dx = c == '>' ? 1
158 : c == '<' ? -1
159 : 0,
160 dy = c == 'v' ? 1
161 : c == '^' ? -1
162 : 0;
163 aoc_assert(dx || dy, "bad warehouse move");
164 int32_t nx = rx + dx, ny = ry + dy;
165 if (map[ny][nx] == '#') {
166 continue;
167 }
168 int32_t count = 0, blocked = 0;
169 stamp++;
170 if (map[ny][nx] != '.') {
171 int32_t bx = nx - (map[ny][nx] == ']');
172 boxes[count++] = ny * w + bx;
173 seen[ny][bx] = stamp;
174 }
175 collect_pushed_boxes(w, wide, &work, stamp, dx, dy, &count, &blocked);
176 if (blocked) {
177 continue;
178 }
179 clear_pushed_boxes(w, wide, count);
180 place_pushed_boxes(w, wide, dx, dy, count);
181 rx = nx;
182 ry = ny;
183 }
184 int64_t sum = 0;
185 for (int32_t y = 0; y < h; y++) {
186 for (int32_t x = 0; x < w; x++) {
187 if (map[y][x] == (wide ? '[' : 'O')) {
188 sum += 100 * y + x;
189 }
190 }
191 }
192 return slice_from_i64(sum);
193}
194
195slice part1(slice s) {
196 return solve(s, 1);
197}
198
199slice part2(slice s) {
200 return solve(s, 2);
201}
202
203const 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
The warehouse robot is already following a supplied move sequence. We are predicting its consequences, not planning a route or solving Sokoban. That distinction saves us from inventing a search over robot actions. Locally the map is 50 by 50, with 603 boxes, 410 wall cells and 20,000 requested moves. Direct simulation is the natural opening, provided each push is handled correctly.
For a narrow box, a push forms a straight chain. Scan along the movement direction until finding empty space or a wall. Empty space lets the chain shift by one cell; a wall cancels the entire move, including the robot's step. The local part-one simulation examines only 6,069 boxes across all move attempts, and the largest successful push contains nine boxes. Even the repeated chain scans are small.
Part two doubles the warehouse width, but that is not the important increase in difficulty. Walls become two cells, boxes become [] and empty tiles become two empty cells, while the robot remains one cell wide and still moves one cell per instruction. Horizontal movement can now leave a box's left edge on an odd coordinate. We cannot keep treating boxes as if they remain aligned to the original doubled grid.
The story's little wide-box example exposes the real turn: one box pushed vertically can overlap two different boxes in the next row. The push no longer has a single chain to follow. It can branch, and the branches can later meet the same box again. Updating the first branch immediately is dangerous: another branch might eventually hit a wall, at which point the story says nothing should have moved. Bummer, a seemingly local push has become an all-or-nothing group operation.
Give each box one identity, represented here by its left cell. Encountering a right bracket redirects us to that left cell. Starting with the box in front of the robot, inspect every destination cell it would occupy after the move. An occupied destination adds that other box to the required moving set. Continue until all dependencies have been explored or a wall blocks any one of them. Deduplicate box identities so converging branches do not move a box twice.
Aha, we can separate discovering the move from performing it. First collect and validate the entire dependency set against the unchanged map. If blocked, discard the proposed move. Otherwise clear every moving box's old cells, then write every box at its translated position, and finally move the robot. Clearing all old cells first avoids one update overwriting another box that has not yet been read. Because every collected box translates by the same vector, their final shapes remain disjoint.
A horizontal wide-box push has a small special-looking case that the identity model resolves naturally: one destination cell may overlap the box's own current footprint. That is not another blocker. Ignore self-contact, but inspect the other destination cell. The same collection routine then handles narrow boxes, horizontal wide boxes and branching vertical pushes without separate movement semantics.
The local widened warehouse is only 100 by 50. Its simulation examines 4,687 boxes, actually fewer than part one, despite the richer logic. It encounters 225 instances of a box depending on two others, and the largest successful push moves fourteen boxes. The difficulty increased because dependencies changed shape, not because the grid became computationally enormous. This is exactly the kind of part-two trap a raw input-size description would miss.
The final GPS sum uses 100 × row + column for each box's left cell, measured from the map edge. The implementation permits width 256 after expansion, height 128, 65,536 moves and two million examined boxes, and requires enclosing walls. Move-sequence line breaks are ignored. The core lesson is to treat a push as a transaction: discover everything that must move, prove it all can move, then apply the change together.
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.