2025 / Day 08
Playground
Read the original puzzle on adventofcode.com ↗
The solution
solution.c
1#include "aoc.h"
2
3/* The local input is 17668 bytes, 1000 lines, longest line 17. There are 1000
4 * junction boxes; the largest coordinate is 99977. BOXES=2048 and COORD=1000000
5 * cover them. Part one keeps only the closest 1000 pairs in a max heap (10 for
6 * the <=20-box example). Pairs within an existing circuit still consume a
7 * connection. Part two uses dense Prim instead of storing half a million edges:
8 * the largest edge in its minimum spanning tree is exactly Kruskal's last
9 * joining edge. Equal distances are ordered by the input indices in both
10 * algorithms. Three circuits must remain for part one. */
11
12static slice line(slice s, size_t *p) {
13 size_t b = *p;
14 while (*p < s.l && s.p[*p] != '\n') {
15 (*p)++;
16 }
17 size_t e = *p;
18 if (*p < s.l) {
19 (*p)++;
20 }
21 if (e > b && s.p[e - 1] == '\r') {
22 e--;
23 }
24 return (slice){s.p + b, e - b};
25}
26
27static uint64_t number(slice s, size_t *p, uint64_t limit) {
28 aoc_assert(*p < s.l && s.p[*p] >= '0' && s.p[*p] <= '9', "bad number");
29 uint64_t n = 0;
30 while (*p < s.l && s.p[*p] >= '0' && s.p[*p] <= '9') {
31 uint64_t d = s.p[(*p)++] - '0';
32 aoc_assert(d <= limit && n <= (limit - d) / 10, "number out of range");
33 n = n * 10 + d;
34 }
35 return n;
36}
37
38static void literal(slice s, size_t *p, const char *t) {
39 size_t n = strlen(t);
40 aoc_assert(*p <= s.l && n <= s.l - *p && memcmp(s.p + *p, t, n) == 0,
41 "bad syntax");
42 *p += n;
43}
44
45enum { BOXES = 2048, COORD = 1000000, CONNECTIONS = 1000 };
46
47static int32_t point[BOXES][3], parent[BOXES], sizes[BOXES];
48
49typedef struct {
50 int64_t distance;
51 int32_t a, b;
52} Edge;
53
54static Edge heap[CONNECTIONS], best[BOXES];
55static uint8_t used[BOXES];
56
57static int compare_edge(const void *aa, const void *bb) {
58 const Edge *a = aa, *b = bb;
59 if (a->distance != b->distance) {
60 return (a->distance > b->distance) - (a->distance < b->distance);
61 }
62 if (a->a != b->a) {
63 return (a->a > b->a) - (a->a < b->a);
64 }
65 return (a->b > b->b) - (a->b < b->b);
66}
67
68static Edge edge(int32_t a, int32_t b) {
69 int64_t distance = 0;
70 for (int32_t k = 0; k < 3; k++) {
71 int64_t d = (int64_t)point[a][k] - point[b][k];
72 distance += d * d;
73 }
74 return (Edge){distance, a < b ? a : b, a < b ? b : a};
75}
76
77static inline __attribute__((always_inline)) size_t
78read_junction_coordinates(int32_t n, slice t, size_t q) {
79 for (int32_t k = 0; k < 3; k++) {
80 point[n][k] = (int32_t)number(t, &q, COORD);
81 if (k < 2) {
82 literal(t, &q, ",");
83 }
84 }
85
86 return q;
87}
88
89static int32_t parse(slice s) {
90 int32_t n = 0;
91 size_t p = 0;
92 while (p < s.l) {
93 slice t = line(s, &p);
94 aoc_assert(n < BOXES, "more than 2048 junction boxes");
95 size_t q = 0;
96 q = read_junction_coordinates(n, t, q);
97 aoc_assert(q == t.l, "bad junction box");
98 n++;
99 }
100 aoc_assert(n >= 2, "need at least two junction boxes");
101 return n;
102}
103
104static int32_t root(int32_t a) {
105 while (parent[a] != a) {
106 parent[a] = parent[parent[a]];
107 a = parent[a];
108 }
109 return a;
110}
111
112static inline __attribute__((always_inline)) int32_t
113raise_connection_heap(int32_t i) {
114 while (i && compare_edge(&heap[i], &heap[(i - 1) / 2]) > 0) {
115 Edge t = heap[i];
116 heap[i] = heap[(i - 1) / 2];
117 heap[(i - 1) / 2] = t;
118 i = (i - 1) / 2;
119 }
120
121 return i;
122}
123
124static inline __attribute__((always_inline)) int32_t
125lower_connection_heap(int32_t count, int32_t i) {
126 while (2 * i + 1 < count) {
127 int32_t c = 2 * i + 1;
128 if (c + 1 < count && compare_edge(&heap[c + 1], &heap[c]) > 0) {
129 c++;
130 }
131 if (compare_edge(&heap[i], &heap[c]) >= 0) {
132 break;
133 }
134 Edge t = heap[i];
135 heap[i] = heap[c];
136 heap[c] = t;
137 i = c;
138 }
139
140 return i;
141}
142
143static inline __attribute__((always_inline)) int32_t
144consider_later_connections(int32_t n, int32_t count, int32_t limit, int32_t a) {
145 for (int32_t b = a + 1; b < n; b++) {
146 Edge e = edge(a, b);
147 if (count < limit) {
148 int32_t i = count++;
149 heap[i] = e;
150 i = raise_connection_heap(i);
151 } else if (compare_edge(&e, &heap[0]) < 0) {
152 heap[0] = e;
153 int32_t i = 0;
154 i = lower_connection_heap(count, i);
155 }
156 }
157
158 return count;
159}
160
161static inline __attribute__((always_inline)) int32_t
162insert_largest_circuit(int32_t top[3], int32_t v) {
163 for (int32_t k = 0; k < 3; k++) {
164 if (v > top[k]) {
165 int32_t t = v;
166 v = top[k];
167 top[k] = t;
168 }
169 }
170
171 return v;
172}
173
174slice part1(slice s) {
175 int32_t n = parse(s), count = 0, limit = n <= 20 ? 10 : CONNECTIONS;
176 for (int32_t a = 0; a < n; a++) {
177 parent[a] = a;
178 sizes[a] = 1;
179 count = consider_later_connections(n, count, limit, a);
180 }
181 qsort(heap, (size_t)count, sizeof(*heap), compare_edge);
182 for (int32_t i = 0; i < count; i++) {
183 int32_t a = root(heap[i].a), b = root(heap[i].b);
184 if (a != b) {
185 if (sizes[a] < sizes[b]) {
186 int32_t t = a;
187 a = b;
188 b = t;
189 }
190 parent[b] = a;
191 sizes[a] += sizes[b];
192 }
193 }
194 int32_t top[3] = {0};
195 for (int32_t i = 0; i < n; i++) {
196 if (root(i) != i) {
197 continue;
198 }
199 int32_t v = sizes[i];
200 v = insert_largest_circuit(top, v);
201 }
202 aoc_assert(top[2] > 0,
203 "fewer than three circuits after the requested connections");
204 return slice_from_i64((int64_t)top[0] * top[1] * top[2]);
205}
206
207static inline __attribute__((always_inline)) int32_t
208choose_next_junction(int32_t n, int32_t v) {
209 for (int32_t i = 0; i < n; i++) {
210 if (!used[i] && (v < 0 || compare_edge(&best[i], &best[v]) < 0)) {
211 v = i;
212 }
213 }
214
215 return v;
216}
217
218static inline __attribute__((always_inline)) void
219update_junction_connections(int32_t n, int32_t v) {
220 for (int32_t i = 0; i < n; i++) {
221 if (!used[i]) {
222 Edge e = edge(v, i);
223 if (compare_edge(&e, &best[i]) < 0) {
224 best[i] = e;
225 }
226 }
227 }
228}
229
230slice part2(slice s) {
231 int32_t n = parse(s);
232 memset(used, 0, sizeof(used));
233 used[0] = 1;
234 for (int32_t i = 1; i < n; i++) {
235 best[i] = edge(0, i);
236 }
237 Edge last = {-1, 0, 0};
238 for (int32_t step = 1; step < n; step++) {
239 int32_t v = -1;
240 v = choose_next_junction(n, v);
241 if (compare_edge(&best[v], &last) > 0) {
242 last = best[v];
243 }
244 used[v] = 1;
245 update_junction_connections(n, v);
246 }
247 return slice_from_i64((int64_t)point[last.a][0] * point[last.b][0]);
248}
249
250const 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 junction boxes float in three dimensions, but the electricity only cares which boxes belong to the same connected circuit. The local input contains 1,000 boxes, with coordinates between 33 and 99,977. There are 499,500 unordered pairs. Calculating every pair's distance and sorting them is entirely plausible: roughly half a million distances and around ten million sorting comparisons. A spatial index might be interesting, but we do not need one to begin solving this input.
Compare squared distances, dx² + dy² + dz². Taking square roots cannot change the ordering of nonnegative distances, and avoiding them keeps comparisons exact. Use a wide integer before multiplying coordinate differences. The local pair distances are all distinct, so there is no ambiguity about which connection comes next.
Maintain a disjoint-set structure: every box initially has its own representative and component size. For each chosen pair, find its two representatives. If they differ, merge the circuits and add their sizes. If they are equal, the new wire does not change connectivity. Path compression and merging smaller components into larger ones keep these operations cheap, without repeatedly traversing the whole growing circuit.
That last case is the first trap. Part one asks for the closest 1,000 pairs, not 1,000 successful component merges. The story deliberately shows a pair already connected through other boxes: its direct connection consumes a place in the list even though the circuit sizes stay unchanged. Locally, 281 of the first 1,000 pairs are redundant in exactly this way. The remaining 719 joins leave 281 circuits, whose three largest sizes are 61, 41 and 36. Skipping redundant pairs until 1,000 merges would not even be possible with only 1,000 boxes.
For this first part, we do not have to retain all half-million edges. Keep a max heap containing the smallest 1,000 seen so far. Its largest retained distance is the threshold a new candidate must beat. Most candidates can be discarded after one comparison; replacing the worst candidate costs only a short heap adjustment. Sort the retained edges and process all of them. The implementation uses ten pairs for inputs of at most 20 boxes, matching the public example, and 1,000 otherwise.
Part two asks us to continue until every box belongs to one circuit, then identify the final joining pair. Reusing the fully sorted list would solve it; locally the final join occurs at pair number 4,536. Notice that only 999 edges ever merge components. All the other processed pairs are cycles. Those successful joins are exactly what Kruskal's minimum-spanning-tree algorithm retains. Recognizing that familiar model lets us compute the decisive edge without retaining the entire sorted list.
The implementation instead uses dense Prim. Start with one connected box and remember, for each outside box, its cheapest edge into the growing tree. Repeatedly choose the cheapest such edge, add its outside endpoint, and update the remaining connection costs. This needs only one best-edge record per box, 499,500 distance calculations locally, and about a million simple candidate scans. The complete graph is implicit in the coordinates, so dense quadratic work is a good fit.
But Prim's last added edge is not necessarily the pair the story asks for. Prim grows outward from one arbitrary starting box, while the story considers all pairs in global distance order. Keep the largest edge anywhere in Prim's resulting tree. With a consistent total ordering of edges, Prim and Kruskal produce the same unique ordered minimum spanning tree; its largest edge is Kruskal's final successful join. That connects the new computation back to the story rather than substituting a merely similar graph problem.
The solver supports up to 2,048 boxes and nonnegative coordinates through one million. Equal squared distances are broken by the original pair indices in both algorithms, providing a deterministic convention for additional inputs. Part one requires at least three circuits after its prescribed connections. Part two returns the product of the final edge's two X coordinates, not its length or the total wire length. The useful abstraction was connectivity; the extra mathematical recognition made its storage small.
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.