2022 / Day 22
Monkey Map
Read the original puzzle on adventofcode.com ↗
The solution
solution.c
1#include "aoc.h"
2
3/* The local input is 25827 bytes, 202 lines, longest line 5625. The local map
4 * is 150 columns by 200 rows, with six 50-by-50 faces; the path is 5625
5 * characters. WIDTH = HEIGHT = 256, PATH = 65536 and WORK = 1000000 bound
6 * traversal. Infer the square face size from area and fold any connected
7 * aligned six-face net using signed 3D basis vectors. Edge transitions match
8 * face normals and edge-axis direction, so the public example's different net
9 * is supported too. */
10
11static slice line(slice s, size_t *p) {
12 size_t b = *p;
13 while (*p < s.l && s.p[*p] != '\n') {
14 (*p)++;
15 }
16 size_t e = *p;
17 if (*p < s.l) {
18 (*p)++;
19 }
20 if (e > b && s.p[e - 1] == '\r') {
21 e--;
22 }
23 return (slice){s.p + b, e - b};
24}
25
26static uint64_t number(slice s, size_t *p, uint64_t limit) {
27 aoc_assert(*p < s.l && s.p[*p] >= '0' && s.p[*p] <= '9', "bad number");
28 uint64_t n = 0;
29 while (*p < s.l && s.p[*p] >= '0' && s.p[*p] <= '9') {
30 uint64_t d = s.p[(*p)++] - '0';
31 aoc_assert(d <= limit && n <= (limit - d) / 10, "number out of range");
32 n = n * 10 + d;
33 }
34 return n;
35}
36
37enum { WIDTH = 256, HEIGHT = 256, PATH = 65536, WORK = 1000000, FACES = 6 };
38
39typedef struct {
40 int8_t v[3];
41} Vector;
42
43typedef struct {
44 int32_t x, y;
45 Vector r, d, n;
46 uint8_t known;
47} Face;
48
49static uint8_t map[HEIGHT][WIDTH];
50static Face faces[FACES];
51static int32_t w, h, side;
52
53static Vector neg(Vector a) {
54 for (int32_t i = 0; i < 3; i++) {
55 a.v[i] = -a.v[i];
56 }
57 return a;
58}
59
60static int32_t same(Vector a, Vector b) {
61 return memcmp(a.v, b.v, 3) == 0;
62}
63
64static int32_t face_at(int32_t x, int32_t y) {
65 for (int32_t i = 0; i < FACES; i++) {
66 if (faces[i].x == x && faces[i].y == y) {
67 return i;
68 }
69 }
70 return -1;
71}
72
73static inline __attribute__((always_inline)) void
74validate_cube_face(int32_t y, int32_t x) {
75 for (int32_t dy = 0; dy < side; dy++) {
76 for (int32_t dx = 0; dx < side; dx++) {
77 aoc_assert(map[y + dy][x + dx], "cube face has a void cell");
78 }
79 }
80}
81
82static inline __attribute__((always_inline)) void
83fold_adjacent_faces(const int32_t dx[4], const int32_t dy[4], Face a) {
84 for (int32_t dir = 0; dir < 4; dir++) {
85 int32_t j = face_at(a.x + dx[dir], a.y + dy[dir]);
86 if (j < 0) {
87 continue;
88 }
89 Vector r = a.r, d = a.d, n = a.n;
90 if (dir == 0) {
91 r = neg(a.n);
92 n = a.r;
93 }
94 if (dir == 2) {
95 r = a.n;
96 n = neg(a.r);
97 }
98 if (dir == 1) {
99 d = neg(a.n);
100 n = a.d;
101 }
102 if (dir == 3) {
103 d = a.n;
104 n = neg(a.d);
105 }
106 if (faces[j].known) {
107 aoc_assert(same(faces[j].r, r) && same(faces[j].d, d) &&
108 same(faces[j].n, n),
109 "inconsistent cube net fold");
110 } else {
111 faces[j].r = r;
112 faces[j].d = d;
113 faces[j].n = n;
114 faces[j].known = 1;
115 }
116 }
117}
118
119static inline __attribute__((always_inline)) void
120propagate_face_orientations(const int32_t dx[4], const int32_t dy[4]) {
121 for (int32_t i = 0; i < FACES; i++) {
122 if (!faces[i].known) {
123 continue;
124 }
125 Face a = faces[i];
126 fold_adjacent_faces(dx, dy, a);
127 }
128}
129
130static inline __attribute__((always_inline)) void
131check_unique_face_normal(int32_t i) {
132 for (int32_t j = 0; j < i; j++) {
133 aoc_assert(!same(faces[i].n, faces[j].n), "cube net overlaps a face");
134 }
135}
136
137static void fold(void) {
138 int32_t area = 0;
139 for (int32_t y = 0; y < h; y++) {
140 for (int32_t x = 0; x < w; x++) {
141 area += map[y][x] != 0;
142 }
143 }
144 side = 1;
145 while (side * side * FACES < area) {
146 side++;
147 }
148 aoc_assert(side * side * FACES == area,
149 "map must contain six equal square faces");
150 int32_t nf = 0;
151 for (int32_t y = 0; y < h; y += side) {
152 for (int32_t x = 0; x < w; x += side) {
153 if (!map[y][x]) {
154 continue;
155 }
156 aoc_assert(nf < FACES && y + side <= h && x + side <= w,
157 "cube faces must align to their square grid");
158 validate_cube_face(y, x);
159 faces[nf++] = (Face){.x = x / side, .y = y / side};
160 }
161 }
162 aoc_assert(nf == FACES, "cube faces must align to their square grid");
163 faces[0].r = (Vector){{1, 0, 0}};
164 faces[0].d = (Vector){{0, 1, 0}};
165 faces[0].n = (Vector){{0, 0, 1}};
166 faces[0].known = 1;
167 const int32_t dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};
168 for (int32_t pass = 0; pass < FACES; pass++) {
169 propagate_face_orientations(dx, dy);
170 }
171 for (int32_t i = 0; i < FACES; i++) {
172 aoc_assert(faces[i].known, "disconnected cube net");
173 check_unique_face_normal(i);
174 }
175}
176
177static void wrap(int32_t x, int32_t y, int32_t dir, int32_t *xx, int32_t *yy,
178 int32_t *dd) {
179 int32_t a = face_at(x / side, y / side);
180 aoc_assert(a >= 0, "missing source face");
181 Face f = faces[a];
182 Vector outward = dir == 0 ? f.r
183 : dir == 1 ? f.d
184 : dir == 2 ? neg(f.r)
185 : neg(f.d);
186 int32_t b = 0;
187 while (b < FACES && !same(faces[b].n, outward)) {
188 b++;
189 }
190 aoc_assert(b < FACES, "missing destination cube face");
191 Face g = faces[b];
192 Vector travel = neg(f.n);
193 int32_t nd = same(travel, g.r) ? 0
194 : same(travel, g.d) ? 1
195 : same(travel, neg(g.r)) ? 2
196 : same(travel, neg(g.d)) ? 3
197 : -1;
198 aoc_assert(nd >= 0, "bad cube edge orientation");
199 int32_t t = dir % 2 ? x % side : y % side;
200 Vector along = dir % 2 ? f.r : f.d, target = nd % 2 ? g.r : g.d;
201 if (!same(along, target)) {
202 aoc_assert(same(along, neg(target)), "bad cube edge axis");
203 t = side - 1 - t;
204 }
205 *xx = g.x * side + (nd == 0 ? 0 : nd == 2 ? side - 1 : t);
206 *yy = g.y * side + (nd == 1 ? 0 : nd == 3 ? side - 1 : t);
207 *dd = nd;
208}
209
210static inline __attribute__((always_inline)) void read_board_row(slice l) {
211 for (size_t x = 0; x < l.l; x++) {
212 aoc_assert(l.p[x] == ' ' || l.p[x] == '.' || l.p[x] == '#',
213 "bad map tile");
214 map[h][x] = l.p[x] == ' ' ? 0 : l.p[x];
215 }
216}
217
218static inline __attribute__((always_inline)) void
219cross_empty_board_cells(int32_t dir, const int32_t dx[4], const int32_t dy[4],
220 int32_t *xx_ref, int32_t *yy_ref,
221 int32_t *attempts_ref) {
222 while (!map[(*yy_ref)][(*xx_ref)]) {
223 aoc_assert(++(*attempts_ref) <= WIDTH + HEIGHT,
224 "row or column has no tile");
225 (*xx_ref) = ((*xx_ref) + dx[dir] + w) % w;
226 (*yy_ref) = ((*yy_ref) + dy[dir] + h) % h;
227 }
228}
229
230static inline __attribute__((always_inline)) void
231walk_board_steps(int32_t part, int32_t *x_ref, int32_t *y_ref, int32_t *dir_ref,
232 int32_t *work_ref, const int32_t dx[4], const int32_t dy[4],
233 int32_t distance) {
234 for (int32_t i = 0; i < distance; i++) {
235 aoc_assert(++(*work_ref) <= WORK,
236 "map walk exceeds 1000000 attempted steps");
237 int32_t xx = (*x_ref) + dx[(*dir_ref)], yy = (*y_ref) + dy[(*dir_ref)],
238 nd = (*dir_ref);
239 if (xx < 0 || xx >= w || yy < 0 || yy >= h || !map[yy][xx]) {
240 if (part == 2) {
241 wrap((*x_ref), (*y_ref), (*dir_ref), &xx, &yy, &nd);
242 } else {
243 xx = (xx + w) % w;
244 yy = (yy + h) % h;
245 int32_t attempts = 0;
246 cross_empty_board_cells((*dir_ref), dx, dy, &xx, &yy,
247 &attempts);
248 }
249 }
250 aoc_assert(map[yy][xx], "cube wrap reaches a void");
251 if (map[yy][xx] == '#') {
252 break;
253 }
254 (*x_ref) = xx;
255 (*y_ref) = yy;
256 (*dir_ref) = nd;
257 }
258}
259
260static slice solve(slice s, int32_t part) {
261 memset(map, 0, sizeof map);
262 size_t p = 0;
263 w = h = 0;
264 while (p < s.l) {
265 slice l = line(s, &p);
266 if (!l.l) {
267 break;
268 }
269 aoc_assert(h < HEIGHT && l.l <= WIDTH, "monkey map too large");
270 if ((int32_t)l.l > w) {
271 w = (int32_t)l.l;
272 }
273 read_board_row(l);
274 h++;
275 }
276 aoc_assert(w > 0 && h > 0, "empty monkey map");
277 slice path = line(s, &p);
278 aoc_assert(p == s.l && path.l > 0 && path.l <= PATH, "bad path length");
279 if (part == 2) {
280 fold();
281 }
282 int32_t x = 0, y = 0, dir = 0, work = 0;
283 while (x < w && map[0][x] != '.') {
284 x++;
285 }
286 aoc_assert(x < w, "no open start on first row");
287 size_t q = 0;
288 const int32_t dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};
289 while (q < path.l) {
290 int32_t distance = (int32_t)number(path, &q, 1000000000);
291 walk_board_steps(part, &x, &y, &dir, &work, dx, dy, distance);
292 if (q < path.l) {
293 aoc_assert(path.p[q] == 'L' || path.p[q] == 'R', "bad path turn");
294 dir = (dir + (path.p[q++] == 'R' ? 1 : 3)) % 4;
295 aoc_assert(q < path.l, "path ends with a turn");
296 }
297 }
298 return slice_from_i64((int64_t)(y + 1) * 1000 + (x + 1) * 4 + dir);
299}
300
301slice part1(slice s) {
302 return solve(s, 1);
303}
304
305slice part2(slice s) {
306 return solve(s, 2);
307}
308
309const 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 map is awkwardly shaped, but the route itself is prescribed. Our local board spans 150 columns and 200 rows, containing 15,000 tiles, of which 1,475 are walls. Its 2,001 forward instructions request 50,549 steps altogether, with 2,000 turns between them. Walking one step at a time is entirely reasonable. This is not a shortest-path problem.
For part one, distinguish a wall from a void. A wall stops the current forward instruction. A void tells us to wrap along the row or column until we reach the opposite occupied part of the board. That destination may itself be a wall, in which case we stay where we were. Spaces in the drawing are therefore meaningful; trimming them away would change both the shape and the coordinates used in the password.
Then we arrive at a cube. Ah. The map was a net, and stepping off an edge can change both our position and our direction as drawn on the paper. The public example has a different net from the local input, so copying a table of its edge connections is not enough.
This is a good moment to make a paper cube or sketch six numbered squares. For one fixed input, carefully deriving its edge table by hand can be the quickest route to a correct answer. The reusable observation is that an edge connection consists of only three facts: destination face, new facing, and whether position along the edge is preserved or reversed. We can derive those facts systematically instead of maintaining many unrelated coordinate cases.
Give each face three perpendicular unit vectors in three-dimensional space: right, down, and outward normal. Start one face with arbitrary axes. Folding its paper neighbor to the right makes that neighbor's normal equal our right vector, its right vector equal our negative normal, and its down vector unchanged. The other three fold directions follow the same quarter-turn idea. Traverse the connected paper net and assign every face an orientation. These vectors contain only -1, 0, and 1; no angles or floating-point arithmetic are necessary.
Now suppose we leave a face through its right edge. The destination face is the one whose normal points in our old right direction. After bending around the edge, our forward motion points along the negative of the old face's normal. Compare that vector with the destination's right and down axes to determine our new local facing. The same construction handles all four departure directions.
One detail remains: which tile along the destination edge? Number the old edge's positions from zero to side - 1. If its increasing direction agrees with the destination edge's increasing direction, keep the number. If they point oppositely, replace it with side - 1 - number. That final reversal is where many plausible-looking hand-written mappings go wrong. With destination, facing, and edge offset settled, the whole wrap is determined.
The six local faces are 50 by 50: six times 50 squared explains the 15,000 occupied tiles. The example instead uses side four. The implementation infers this size from area, validates complete aligned square faces, and checks that folding gives six distinct normals. A disconnected or overlapping net is rejected.
Before committing a cube crossing, inspect its destination tile. If it is a wall, keep both the old position and old facing. Rotating despite a blocked move corrupts every later instruction. At the end, convert to the original map's one-based row and column and use the prescribed facing code in the password.
Maps are bounded to 256 by 256, the path to 65,536 characters, and traversal to one million attempted steps. The breakthrough is not a faster walker. It is replacing a pile of special edge cases with a small geometric description that makes every crossing answer the same three questions.
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.