2016 / Day 22
Grid Computing
Read the original puzzle on adventofcode.com ↗
The solution
solution.c
1#include "aoc.h"
2
3/* A complete grid <= 64x64, sizes <= 1e6. Part 2 validates the sliding
4 * model: one empty node, every movable payload fits every movable node,
5 * two payloads cannot merge, and walls cannot send or receive data.
6 * Only then is (empty position, goal position) the full search state. */
7enum { SIDE = 64, CELLS = SIDE * SIDE, STATES = 250000, HASH = 524288 };
8
9struct node {
10 int32_t size, used;
11 uint8_t present;
12};
13static struct node nodes[CELLS];
14static uint8_t walls[CELLS];
15static uint32_t keys[2][HASH], queue_[2][STATES];
16static int w, h, count;
17
18static int take(slice line, size_t *i, const char *s) {
19 size_t n = strlen(s);
20 if (n <= line.l - *i && !memcmp(line.p + *i, s, n)) {
21 *i += n;
22 return 1;
23 }
24 return 0;
25}
26
27static int number(slice line, size_t *i) {
28 while (*i < line.l && (line.p[*i] == ' ' || line.p[*i] == '\t')) {
29 (*i)++;
30 }
31 size_t start = *i;
32 int32_t v = 0;
33 while (*i < line.l && line.p[*i] >= '0' && line.p[*i] <= '9') {
34 int digit = line.p[(*i)++] - '0';
35 aoc_assert(v <= (1000000 - digit) / 10, "bad node number");
36 v = 10 * v + digit;
37 }
38 aoc_assert(*i > start, "bad node number");
39 return v;
40}
41
42static int terabytes(slice line, size_t *i) {
43 int v = number(line, i);
44 aoc_assert(take(line, i, "T"), "bad node line");
45 return v;
46}
47
48static void load(slice in) {
49 memset(nodes, 0, sizeof nodes);
50 w = h = count = 0;
51 size_t i = 0;
52 int headers = 0;
53 while (i < in.l) {
54 size_t e = i;
55 while (e < in.l && in.p[e] != '\n') {
56 e++;
57 }
58 size_t end = e;
59 if (end > i && in.p[end - 1] == '\r') {
60 end--;
61 }
62 slice line = {in.p + i, end - i};
63 size_t p = 0;
64 if (take(line, &p, "/dev/grid/node-x")) {
65 int x = number(line, &p);
66 aoc_assert(take(line, &p, "-y"), "bad node line");
67 int y = number(line, &p);
68 aoc_assert(x < SIDE && y < SIDE, "grid exceeds cap");
69 int size = terabytes(line, &p), used = terabytes(line, &p),
70 avail = terabytes(line, &p);
71 int percent = number(line, &p);
72 aoc_assert(take(line, &p, "%"), "bad node line");
73 while (p < line.l && (line.p[p] == ' ' || line.p[p] == '\t')) {
74 p++;
75 }
76 aoc_assert(p == line.l && size > 0 && used + avail == size &&
77 percent <= 100,
78 "bad node line");
79 int cell = y * SIDE + x;
80 aoc_assert(!nodes[cell].present, "duplicate node");
81 nodes[cell] = (struct node){size, used, 1};
82 if (x + 1 > w) {
83 w = x + 1;
84 }
85 if (y + 1 > h) {
86 h = y + 1;
87 }
88 count++;
89 } else {
90 aoc_assert(
91 !count && headers++ < 2 &&
92 (take(line, &p, "root@") || take(line, &p, "Filesystem")),
93 "bad node line");
94 }
95 i = e < in.l ? e + 1 : e;
96 }
97 aoc_assert(count > 0 && count == w * h, "incomplete grid");
98 for (int y = 0; y < h; y++) {
99 for (int x = 0; x < w; x++) {
100 aoc_assert(nodes[y * SIDE + x].present, "incomplete grid");
101 nodes[y * w + x] = nodes[y * SIDE + x];
102 }
103 }
104}
105
106slice part1(slice in) {
107 load(in);
108 int64_t pairs = 0;
109 for (int a = 0; a < count; a++) {
110 if (nodes[a].used) {
111 for (int b = 0; b < count; b++) {
112 pairs +=
113 a != b && nodes[a].used <= nodes[b].size - nodes[b].used;
114 }
115 }
116 }
117 return slice_from_i64(pairs);
118}
119
120static int model(void) {
121 int empty = -1;
122 for (int k = 0; k < count; k++) {
123 if (!nodes[k].used) {
124 aoc_assert(empty < 0, "sliding model needs one empty node");
125 empty = k;
126 }
127 }
128 aoc_assert(empty >= 0, "sliding model needs one empty node");
129 int minsize = INT32_MAX, maxsize = 0, minused = INT32_MAX, maxused = 0;
130 for (int k = 0; k < count; k++) {
131 walls[k] = nodes[k].used > nodes[empty].size;
132 if (walls[k]) {
133 continue;
134 }
135 if (nodes[k].size < minsize) {
136 minsize = nodes[k].size;
137 }
138 if (nodes[k].size > maxsize) {
139 maxsize = nodes[k].size;
140 }
141 if (nodes[k].used && nodes[k].used < minused) {
142 minused = nodes[k].used;
143 }
144 if (nodes[k].used > maxused) {
145 maxused = nodes[k].used;
146 }
147 }
148 aoc_assert(maxused > 0 && maxused <= minsize && 2 * minused > maxsize,
149 "payloads do not fit sliding model");
150 for (int k = 0; k < count; k++) {
151 if (walls[k]) {
152 aoc_assert(nodes[k].used > maxsize &&
153 nodes[k].size - nodes[k].used < minused,
154 "wall can exchange data");
155 int x = k % w, y = k / w;
156 int next[4] = {x ? k - 1 : -1, x + 1 < w ? k + 1 : -1,
157 y ? k - w : -1, y + 1 < h ? k + w : -1};
158 for (int d = 0; d < 4; d++) {
159 int q = next[d];
160 if (q >= 0 && walls[q]) {
161 aoc_assert(nodes[k].used > nodes[q].size - nodes[q].used,
162 "walls can exchange data");
163 }
164 }
165 }
166 }
167 aoc_assert(!walls[0] && !walls[w - 1] && nodes[w - 1].used > 0,
168 "goal outside sliding model");
169 return empty;
170}
171
172/* State uses 24 bits; the high byte stores depth+1. BFS from the
173 * initial state and all states whose goal has reached (0,0). */
174static size_t slot(int side, uint32_t state) {
175 size_t index = (state * 2654435761u) & (HASH - 1);
176 for (int n = 0; n < HASH; n++) {
177 uint32_t k = keys[side][index];
178 if (!k || (k & 0xffffffu) == state) {
179 return index;
180 }
181 index = (index + 1) & (HASH - 1);
182 }
183 aoc_assert(0, "grid state table full");
184}
185
186slice part2(slice in) {
187 load(in);
188 int empty = model();
189 if (w == 1) {
190 return slice_from_i64(0);
191 }
192 memset(keys, 0, sizeof keys);
193 uint32_t initial = (uint32_t)((w - 1) * CELLS + empty);
194 int head[2] = {0, 0}, tail[2] = {1, 0};
195 queue_[0][0] = initial;
196 keys[0][slot(0, initial)] = initial | (1u << 24);
197 for (int e = 1; e < count; e++) {
198 if (!walls[e]) {
199 uint32_t state = (uint32_t)e;
200 queue_[1][tail[1]++] = state;
201 keys[1][slot(1, state)] = state | (1u << 24);
202 }
203 }
204 while (head[0] < tail[0] && head[1] < tail[1]) {
205 int side = tail[0] - head[0] <= tail[1] - head[1] ? 0 : 1;
206 int end = tail[side], best = INT32_MAX;
207 while (head[side] < end) {
208 uint32_t state = queue_[side][head[side]++];
209 int depth = (int)(keys[side][slot(side, state)] >> 24) - 1;
210 aoc_assert(depth < 254, "grid depth exceeds cap");
211 int e = state % CELLS, goal = state / CELLS;
212 int x = e % w, y = e / w;
213 int next[4] = {x ? e - 1 : -1, x + 1 < w ? e + 1 : -1,
214 y ? e - w : -1, y + 1 < h ? e + w : -1};
215 for (int d = 0; d < 4; d++) {
216 int q = next[d];
217 if (q < 0 || walls[q]) {
218 continue;
219 }
220 uint32_t target =
221 (uint32_t)((q == goal ? e : goal) * CELLS + q);
222 size_t index = slot(side, target);
223 if (keys[side][index]) {
224 continue;
225 }
226 aoc_assert(tail[side] < STATES,
227 "grid search exceeds state cap");
228 keys[side][index] = target | ((uint32_t)(depth + 2) << 24);
229 queue_[side][tail[side]++] = target;
230 size_t other = slot(1 - side, target);
231 if (keys[1 - side][other]) {
232 int distance = depth + (int)(keys[1 - side][other] >> 24);
233 if (distance < best) {
234 best = distance;
235 }
236 }
237 }
238 }
239 if (best != INT32_MAX) {
240 return slice_from_i64(best);
241 }
242 }
243 aoc_assert(0, "goal unreachable");
244}
245
246static slice estimate(slice in) {
247 load(in);
248 model();
249 return slice_from_i64((int64_t)count * count);
250}
251
252const struct aoc_method aoc_methods[] = {
253 {"estimate", estimate},
254 {0, 0},
255};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
Part 1 asks about possible transfers, but explicitly ignores adjacency. For each nonempty source A, compare its used space with every other node B's available space. The pair is directed: A fitting into B does not imply B fitting into A. The local grid is 33 by 31, with 1,023 nodes, so checking all distinct ordered pairs takes at most about 1.05 million comparisons. That straightforward loop is already a sensible solution.
Part 2 asks us to start moving things. Suddenly adjacency matters, capacities change, and the important data can travel between nodes. Remembering every payload in every possible arrangement sounds dreadful. The example's little drawing offers hope: perhaps this is a sliding puzzle. But earn that simplification before using it. The actual rules allow data to move into a nonempty node if it fits, merging payloads. Where is the evidence that our grid cannot do that?
Look at the capacity ranges. There is one empty node at (3,28), capacity 88T. The 991 ordinary nodes hold 85–94T, and their nonempty payloads are 64–73T. Two small inequalities do an extraordinary amount of work: 73 ≤ 85 means every payload fits any empty ordinary node; 64 + 64 > 94 means no two ordinary payloads fit together. A legal ordinary transfer really must exchange a payload with the empty space. The sliding-puzzle intuition is becoming a model we can defend.
The remaining 32 nodes form a wall at y = 20, from x = 1 through x = 32. Their payloads are 490–499T, too large for any ordinary node, while their available space is only 3–18T, too small to receive an ordinary payload or a neighboring wall's payload. They cannot change. These inequalities make the reduction stable after future moves: normal transfers preserve the payload sizes, and the walls never participate. Drawing the empty node, this wall, and the goal now reveals a sliding puzzle justified by the data.
Now imagine swapping two ordinary payload labels. Every possible move stays legal. We can forget those labels entirely and remember just two positions: the empty node and the goal data. Moving into the hole relocates the hole; if the moved payload was the goal, update that position too. This is the payoff for inspecting the input: a terrifying arrangement of a thousand payloads shrinks to at most about a million position pairs, before excluding walls and impossible combinations.
For a manual solve, watch how the empty space travels around the wall's open end and gets to the left of the goal. After shifting the goal left, it must circle around to get ahead again. In an unobstructed two-row strip that cycle costs five moves per further left shift. This is a useful plan to inspect, not a universal formula for arbitrary grids. The implementation instead uses bidirectional breadth-first search on the reduced states, preserving shortest-path guarantees even when the geometry is less convenient. The reverse search starts from all allowed empty positions with the goal at (0,0).
The solver accepts complete grids up to 64 by 64 and capacities through one million. Part 2 validates the single empty node, payload inequalities, and immovable walls before searching; inputs that permit merging are explicitly outside this model. Each search side has a 250,000-state cap and depths below 255. The estimate method validates the model and reports the loose node-count-squared state bound. The measurements make this reduction credible; the runtime checks make its use conditional rather than hopeful.
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.