2018 / Day 23
Experimental Emergency Teleportation
Read the original puzzle on adventofcode.com ↗
The solution
solution.c
1#include "aoc.h"
2
3typedef struct {
4 slice s;
5 size_t i;
6} Parser;
7
8static int space(uint8_t c) {
9 return c == ' ' || c == '\t' || c == '\r' || c == '\n';
10}
11
12static void ws(Parser *p) {
13 while (p->i < p->s.l && space(p->s.p[p->i])) {
14 p->i++;
15 }
16}
17
18static void text(Parser *p, const char *s) {
19 size_t n = strlen(s);
20 aoc_assert(n <= p->s.l - p->i && !memcmp(p->s.p + p->i, s, n), "bad input");
21 p->i += n;
22}
23
24static int64_t number(Parser *p, int64_t cap) {
25 int neg = 0;
26 int64_t v = 0;
27 if (p->i < p->s.l && (p->s.p[p->i] == '-' || p->s.p[p->i] == '+')) {
28 neg = p->s.p[p->i++] == '-';
29 }
30 size_t start = p->i;
31 while (p->i < p->s.l && p->s.p[p->i] >= '0' && p->s.p[p->i] <= '9') {
32 int d = p->s.p[p->i++] - '0';
33 aoc_assert(v <= (cap - d) / 10 && d <= cap, "integer exceeds cap");
34 v = v * 10 + d;
35 }
36 aoc_assert(p->i > start, "expected integer");
37 return neg ? -v : v;
38}
39
40static void finish(Parser *p) {
41 ws(p);
42 aoc_assert(p->i == p->s.l, "trailing input");
43}
44
45static slice line(Parser *p) {
46 size_t b = p->i;
47 while (p->i < p->s.l && p->s.p[p->i] != '\n') {
48 p->i++;
49 }
50 size_t e = p->i;
51 if (e > b && p->s.p[e - 1] == '\r') {
52 e--;
53 }
54 if (p->i < p->s.l) {
55 p->i++;
56 }
57 return (slice){b ? p->s.p + b : p->s.p, e - b};
58}
59
60static int64_t absolute(int64_t x) {
61 return x < 0 ? -x : x;
62}
63
64typedef struct {
65 int64_t x, y, z, r;
66} Bot;
67
68/* Points inside the radii are not enumerated. A bot meets a cube
69 * exactly when its Manhattan distance to the cube is within its radius,
70 * which is an upper bound on how many bots can cover any point of that
71 * cube. The cube's distance to the origin is a lower bound on the
72 * tie-break. Best-first subdivision — coverage, then that distance,
73 * then size — returns the first unit cube, and that cube has the best
74 * coverage and distance. Part 1 is only the count inside the strongest
75 * bot's radius.
76 *
77 * The file is assumed to be at most BOTS bots, coordinates and radii
78 * inside COORD, radii nonnegative, searched inside HEAP queued cubes
79 * and WORK bot/cube tests. A bad line, a negative radius, or an empty
80 * file is refused ("bad input", "integer exceeds cap", "expected
81 * integer", "trailing input", "too many bots", "negative radius",
82 * "empty bots"). A search past the caps is "nanobot queue exceeds cap",
83 * "nanobot search exceeds cap", or "no covered point". BOTS is 1024, so
84 * each cube is a short pass over the bots rather than a scan of the
85 * coordinate box.
86 *
87 * The real file is 1000 bots. Coordinates run from -151734092 to 226831435 and
88 * radii from 49770806 to 99277279, so the covered volume is not a grid to
89 * scan. Each test is one bot against one cube. BOTS = 1024 and COORD =
90 * 1000000000 are the refusals above that list.
91 */
92enum { BOTS = 1024 };
93
94enum { COORD = 1000000000 };
95
96enum { HEAP = 65536 };
97
98enum { WORK = 20000000 };
99
100static Bot bots[BOTS];
101static int n, work;
102
103typedef struct {
104 int64_t x, y, z, size, dist;
105 int count;
106} Box;
107
108static Box heap[HEAP];
109static int hn;
110
111static void load(slice in) {
112 Parser p = {in, 0};
113 n = 0;
114 while (p.i < in.l) {
115 aoc_assert(n < BOTS, "too many bots");
116 Parser q = {line(&p), 0};
117 text(&q, "pos=<");
118 int64_t x = number(&q, COORD);
119 text(&q, ",");
120 int64_t y = number(&q, COORD);
121 text(&q, ",");
122 int64_t z = number(&q, COORD);
123 text(&q, ">, r=");
124 int64_t r = number(&q, COORD);
125 finish(&q);
126 aoc_assert(r >= 0, "negative radius");
127 bots[n++] = (Bot){x, y, z, r};
128 }
129 aoc_assert(n, "empty bots");
130}
131
132static int64_t axis(int64_t point, int64_t low, int64_t size) {
133 return point < low ? low - point
134 : point >= low + size ? point - (low + size - 1)
135 : 0;
136}
137
138static int better(Box a, Box b) {
139 return a.count > b.count ||
140 (a.count == b.count &&
141 (a.dist < b.dist || (a.dist == b.dist && a.size < b.size)));
142}
143
144static void push(Box b) {
145 b.dist = axis(0, b.x, b.size) + axis(0, b.y, b.size) + axis(0, b.z, b.size);
146 b.count = 0;
147 for (int i = 0; i < n; i++) {
148 aoc_assert(++work <= WORK, "nanobot search exceeds cap");
149 Bot a = bots[i];
150 b.count += axis(a.x, b.x, b.size) + axis(a.y, b.y, b.size) +
151 axis(a.z, b.z, b.size) <=
152 a.r;
153 }
154 if (!b.count) {
155 return;
156 }
157 aoc_assert(hn < HEAP, "nanobot queue exceeds cap");
158 int k = hn++;
159 while (k && better(b, heap[(k - 1) / 2])) {
160 heap[k] = heap[(k - 1) / 2];
161 k = (k - 1) / 2;
162 }
163 heap[k] = b;
164}
165
166static Box pop(void) {
167 Box b = heap[0], e = heap[--hn];
168 int k = 0;
169 while (2 * k + 1 < hn) {
170 int c = 2 * k + 1;
171 if (c + 1 < hn && better(heap[c + 1], heap[c])) {
172 c++;
173 }
174 if (!better(heap[c], e)) {
175 break;
176 }
177 heap[k] = heap[c];
178 k = c;
179 }
180 if (hn) {
181 heap[k] = e;
182 }
183 return b;
184}
185
186slice part1(slice in) {
187 load(in);
188 int best = 0, count = 0;
189 for (int i = 1; i < n; i++) {
190 if (bots[i].r > bots[best].r) {
191 best = i;
192 }
193 }
194 Bot b = bots[best];
195 for (int i = 0; i < n; i++) {
196 count += absolute(b.x - bots[i].x) + absolute(b.y - bots[i].y) +
197 absolute(b.z - bots[i].z) <=
198 b.r;
199 }
200 return slice_from_i64(count);
201}
202
203static inline __attribute__((always_inline)) void
204extend_bot_bounds(int64_t lo[3], int64_t hi[3], int i, int64_t v[3]) {
205 for (int k = 0; k < 3; k++) {
206 if (v[k] - bots[i].r < lo[k]) {
207 lo[k] = v[k] - bots[i].r;
208 }
209 if (v[k] + bots[i].r > hi[k]) {
210 hi[k] = v[k] + bots[i].r;
211 }
212 }
213}
214
215static inline __attribute__((always_inline)) void
216subdivide_search_box(Box b, int64_t half) {
217 for (int k = 0; k < 8; k++) {
218 push((Box){b.x + ((k & 1) ? half : 0), b.y + ((k & 2) ? half : 0),
219 b.z + ((k & 4) ? half : 0), half, 0, 0});
220 }
221}
222
223slice part2(slice in) {
224 load(in);
225 int64_t lo[3] = {INT64_MAX, INT64_MAX, INT64_MAX},
226 hi[3] = {INT64_MIN, INT64_MIN, INT64_MIN};
227 for (int i = 0; i < n; i++) {
228 int64_t v[3] = {bots[i].x, bots[i].y, bots[i].z};
229 extend_bot_bounds(lo, hi, i, v);
230 }
231 int64_t size = 1;
232 while (size <= hi[0] - lo[0] || size <= hi[1] - lo[1] ||
233 size <= hi[2] - lo[2]) {
234 size *= 2;
235 }
236 hn = work = 0;
237 push((Box){lo[0], lo[1], lo[2], size, 0, 0});
238 while (hn) {
239 Box b = pop();
240 if (b.size == 1) {
241 return slice_from_i64(b.dist);
242 }
243 int64_t half = b.size / 2;
244 subdivide_search_box(b, half);
245 }
246 aoc_assert(0, "no covered point");
247}
248
249const struct aoc_method aoc_methods[] = {
250 {0, 0},
251};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 one asks about the strongest transmitter. Find the largest radius, then test every bot's position against that one radius. The local input has one thousand bots, so a thousand Manhattan-distance checks after a maximum scan are enough. The receiving bots' own radii do not matter to this question; being in another bot's range is not necessarily mutual.
Part two reverses the viewpoint. We are choosing a receiving position that hears the most bots. The strongest bot's center is no longer special, and the best position need not be any bot's center. Coverage comes first; distance to the origin breaks ties only among equally well-covered positions. Trading one lost signal for a much shorter distance would violate that ordering.
Inspect the scale before trying a grid. Local coordinates range from about -152 million to 227 million, and radii are roughly fifty to one hundred million. A power-of-two cube covering every signal extent has side 1,073,741,824, containing about 1.24 × 10^27 integer positions. Even very cheap point tests cannot make exhaustive enumeration plausible.
A coarse grid followed by a finer search around its best sampled point is an inviting experiment. It might find a good candidate, but sampling can miss a narrow overlap between large signal regions. Keeping only one promising coarse location can discard the true optimum. We need a way to ask what might be possible anywhere in a region, rather than pretending its sampled center represents every point inside it.
For an axis-aligned cube, the nearest Manhattan distance from a bot is easy to compute. On each axis, contribute zero if the bot's coordinate lies inside the cube's interval; otherwise contribute the gap to the nearer endpoint. Add the three gaps. If that sum exceeds the bot's radius, no point in the cube hears it. Otherwise at least one point in the cube does.
Count the bots whose ranges intersect the cube. That is an upper bound on the coverage of any single point inside. The distinction matters: different bots may touch different corners without sharing one common covered point. The count is optimistic, not a claim that its coverage is attainable. Similarly, the nearest distance from the cube to the origin is a lower bound on the distance of any point inside.
Now keep a queue of cubes ordered by greatest possible coverage, then least possible distance, then smaller size. Split the most promising cube into eight children and recompute their bounds. Empty children can be discarded. Promising children stay in competition with all the other unresolved regions, so a locally attractive cube does not make us forget a better possibility elsewhere. This is branch-and-bound search driven by geometric evidence.
At side length one, the cube is an actual integer point and both bounds become exact. The first such point removed from the ordered queue is optimal: no remaining cube can promise higher coverage, or a shorter distance at equal coverage. Size is only a later tie-break to encourage progress; it must not override the two objectives in the question.
On the local input, an independent run reaches a point covered by 976 bots after removing only 95 cubes from the queue and performing 753,000 bot-versus-cube tests. That is the enormous reduction we were looking for, grounded in bounds rather than a lucky sampling resolution. The implementation accepts at most 1,024 bots, coordinate magnitudes and radii through one billion, nonnegative radii, 65,536 queued cubes, and twenty million bot/cube tests. It explicitly refuses a search that exceeds those limits instead of returning the best guess seen so far.
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.