2023 / Day 24
Never Tell Me The Odds
Read the original puzzle on adventofcode.com ↗
The solution
solution.c
1#include "aoc.h"
2
3/* The local input is 19703 bytes, 300 lines, longest line 68. There are 300
4 * hailstones, positions up to 545802384484064 and velocity magnitude up to 886.
5 * STONES = 512, POSITION = 10^15 and VELOCITY = 1024 bound parsing. Part 1
6 * compares rational intersections with manual signed 128-bit products, avoiding
7 * floating boundary errors. As in the public example, all-small positions
8 * (magnitude at most 1000) select [7,27]; otherwise use [2e14,4e14]. Part 2
9 * tries nondegenerate triples among the first 12 stones, rounds a floating
10 * linear solve to an integral rock, and verifies every collision by exact
11 * reduced rational time. A numerically unresolved or nonintegral rock is
12 * explicitly refused; accepted rock velocities are bounded by 4096. Parallel
13 * collinear rays are clipped by exact rational time intervals; stationary
14 * projected paths are supported too. Each intersecting pair counts once. */
15
16static slice line(slice s, size_t *p) {
17 size_t b = *p;
18 while (*p < s.l && s.p[*p] != '\n') {
19 (*p)++;
20 }
21 size_t e = *p;
22 if (*p < s.l) {
23 (*p)++;
24 }
25 if (e > b && s.p[e - 1] == '\r') {
26 e--;
27 }
28 return (slice){s.p + b, e - b};
29}
30
31static void spaces(slice s, size_t *p) {
32 while (*p < s.l && (s.p[*p] == ' ' || s.p[*p] == '\n' || s.p[*p] == '\r' ||
33 s.p[*p] == '\t')) {
34 (*p)++;
35 }
36}
37
38static uint64_t number(slice s, size_t *p, uint64_t limit) {
39 aoc_assert(*p < s.l && s.p[*p] >= '0' && s.p[*p] <= '9', "bad number");
40 uint64_t n = 0;
41 while (*p < s.l && s.p[*p] >= '0' && s.p[*p] <= '9') {
42 uint64_t d = s.p[(*p)++] - '0';
43 aoc_assert(d <= limit && n <= (limit - d) / 10, "number out of range");
44 n = n * 10 + d;
45 }
46 return n;
47}
48
49static int64_t signed_number(slice s, size_t *p, int64_t limit) {
50 int32_t neg = *p < s.l && s.p[*p] == '-';
51 if (neg) {
52 (*p)++;
53 }
54 int64_t v = (int64_t)number(s, p, (uint64_t)limit);
55 return neg ? -v : v;
56}
57
58static void literal(slice s, size_t *p, const char *t) {
59 size_t n = strlen(t);
60 aoc_assert(*p <= s.l && n <= s.l - *p && memcmp(s.p + *p, t, n) == 0,
61 "bad syntax");
62 *p += n;
63}
64
65static int64_t abs64(int64_t x) {
66 return x < 0 ? -x : x;
67}
68
69enum { STONES = 512, VELOCITY = 1024, ROCK_VELOCITY = 4096, TRIAL_STONES = 12 };
70
71#define POSITION INT64_C(1000000000000000)
72
73typedef struct {
74 int64_t p[3], v[3];
75} Stone;
76
77static Stone stones[STONES];
78
79typedef struct {
80 uint64_t hi, lo;
81} Wide;
82
83static Wide wide_product(int64_t a, int64_t b) {
84 uint64_t x = a < 0 ? (uint64_t)-a : (uint64_t)a,
85 y = b < 0 ? (uint64_t)-b : (uint64_t)b, x0 = (uint32_t)x,
86 x1 = x >> 32, y0 = (uint32_t)y, y1 = y >> 32, p = x0 * y0,
87 q = x0 * y1, r = x1 * y0;
88 Wide z = {x1 * y1 + (q >> 32) + (r >> 32), p};
89 uint64_t old = z.lo;
90 z.lo += q << 32;
91 z.hi += z.lo < old;
92 old = z.lo;
93 z.lo += r << 32;
94 z.hi += z.lo < old;
95 if ((a < 0) != (b < 0)) {
96 z.lo = ~z.lo + 1;
97 z.hi = ~z.hi + (z.lo == 0);
98 }
99 return z;
100}
101
102static int32_t nonnegative_sum(Wide a, Wide b) {
103 uint64_t lo = a.lo + b.lo, hi = a.hi + b.hi + (lo < a.lo);
104 return !(hi >> 63);
105}
106
107static int32_t bound(int64_t p, int64_t v, int64_t num, int64_t den,
108 int64_t edge, int32_t above) {
109 Wide a = wide_product(p - edge, den), b = wide_product(v, num);
110 if (above) {
111 return nonnegative_sum(a, b);
112 }
113 a.lo = ~a.lo + 1;
114 a.hi = ~a.hi + (a.lo == 0);
115 b.lo = ~b.lo + 1;
116 b.hi = ~b.hi + (b.lo == 0);
117 return nonnegative_sum(a, b);
118}
119
120static int64_t gcd64(int64_t a, int64_t b) {
121 a = abs64(a);
122 b = abs64(b);
123 while (b) {
124 int64_t t = a % b;
125 a = b;
126 b = t;
127 }
128 return a;
129}
130
131static inline __attribute__((always_inline)) int
132verify_rock_axes(int64_t *r, int32_t i, int32_t *have_ref,
133 int64_t *numerator_ref, int64_t *denominator_ref,
134 int32_t *answer_out) {
135 for (int32_t k = 0; k < 3; k++) {
136 int64_t dp = stones[i].p[k] - r[k], dv = r[k + 3] - stones[i].v[k];
137 if (!dv) {
138 if (dp) {
139 {
140 *answer_out = 0;
141 return 1;
142 };
143 }
144 continue;
145 }
146 if (dv < 0) {
147 dp = -dp;
148 dv = -dv;
149 }
150 if (dp < 0) {
151 {
152 *answer_out = 0;
153 return 1;
154 };
155 }
156 int64_t g = gcd64(dp, dv), a = dp / g, b = dv / g;
157 if ((*have_ref) && (a != (*numerator_ref) || b != (*denominator_ref))) {
158 {
159 *answer_out = 0;
160 return 1;
161 };
162 }
163 (*numerator_ref) = a;
164 (*denominator_ref) = b;
165 (*have_ref) = 1;
166 }
167
168 return 0;
169}
170
171static int32_t verify(int32_t n, int64_t *r) {
172 for (int32_t i = 0; i < 3; i++) {
173 if (abs64(r[i]) > POSITION || abs64(r[i + 3]) > ROCK_VELOCITY) {
174 return 0;
175 }
176 }
177 for (int32_t i = 0; i < n; i++) {
178 int32_t have = 0;
179 int64_t numerator = 0, denominator = 1;
180 {
181 int32_t answer;
182 if (verify_rock_axes(r, i, &have, &numerator, &denominator,
183 &answer)) {
184 return answer;
185 }
186 }
187 }
188 return 1;
189}
190
191typedef struct {
192 int64_t n, d;
193} Rational;
194
195static Rational rational(int64_t n, int64_t d) {
196 if (d < 0) {
197 n = -n;
198 d = -d;
199 }
200 return (Rational){n, d};
201}
202
203static int less(Rational a, Rational b) {
204 return a.n * b.d < b.n * a.d;
205}
206
207static int parallel(Stone *a, Stone *b, int64_t low, int64_t high) {
208 int movinga = a->v[0] || a->v[1], movingb = b->v[0] || b->v[1];
209 if (!movinga || !movingb) {
210 Stone *fixed = movinga ? b : a, *moving = movinga ? a : b;
211 if (fixed->p[0] < low || fixed->p[0] > high || fixed->p[1] < low ||
212 fixed->p[1] > high) {
213 return 0;
214 }
215 int64_t dx = fixed->p[0] - moving->p[0],
216 dy = fixed->p[1] - moving->p[1];
217 if (!movinga && !movingb) {
218 return !dx && !dy;
219 }
220 if (dx * moving->v[1] != dy * moving->v[0]) {
221 return 0;
222 }
223 int axis = moving->v[0] ? 0 : 1;
224 int64_t num = fixed->p[axis] - moving->p[axis], den = moving->v[axis];
225 return !num || (num < 0) == (den < 0);
226 }
227 int64_t dx = b->p[0] - a->p[0], dy = b->p[1] - a->p[1];
228 if (dx * a->v[1] != dy * a->v[0]) {
229 return 0;
230 }
231 Rational lo = {0, 1}, hi = {0, 1};
232 int upper = 0;
233 for (int k = 0; k < 2; k++) {
234 if (!a->v[k]) {
235 if (a->p[k] < low || a->p[k] > high) {
236 return 0;
237 }
238 continue;
239 }
240 Rational first = rational(low - a->p[k], a->v[k]),
241 last = rational(high - a->p[k], a->v[k]);
242 if (less(last, first)) {
243 Rational t = first;
244 first = last;
245 last = t;
246 }
247 if (less(lo, first)) {
248 lo = first;
249 }
250 if (!upper || less(last, hi)) {
251 hi = last;
252 upper = 1;
253 }
254 }
255 int axis = a->v[0] ? 0 : 1;
256 Rational start = rational(b->p[axis] - a->p[axis], a->v[axis]);
257 if ((a->v[axis] < 0) == (b->v[axis] < 0)) {
258 if (less(lo, start)) {
259 lo = start;
260 }
261 } else if (less(start, hi)) {
262 hi = start;
263 }
264 return !less(hi, lo);
265}
266
267static double absolute(double x) {
268 return x < 0 ? -x : x;
269}
270
271static inline __attribute__((always_inline)) void
272subtract_stone_vectors(Stone *x, Stone *y, int64_t dp[3], int64_t dv[3]) {
273 for (int32_t k = 0; k < 3; k++) {
274 dp[k] = y->p[k] - x->p[k];
275 dv[k] = y->v[k] - x->v[k];
276 }
277}
278
279static inline __attribute__((always_inline)) void
280build_rock_equations(double m[6][7], Stone *x, Stone *y, int64_t dp[3],
281 int64_t dv[3], int32_t row) {
282 for (int32_t k = 0; k < 3; k++) {
283 int32_t i = (k + 1) % 3, j = (k + 2) % 3;
284 m[row + k][i] = (double)dv[j];
285 m[row + k][j] = -(double)dv[i];
286 m[row + k][3 + i] = -(double)dp[j];
287 m[row + k][3 + j] = (double)dp[i];
288 m[row + k][6] = (double)(y->p[i] * y->v[j] - y->p[j] * y->v[i]) -
289 (double)(x->p[i] * x->v[j] - x->p[j] * x->v[i]);
290 }
291}
292
293static inline __attribute__((always_inline)) int32_t
294select_matrix_pivot(double m[6][7], int32_t col, int32_t pivot) {
295 for (int32_t row = col + 1; row < 6; row++) {
296 if (absolute(m[row][col]) > absolute(m[pivot][col])) {
297 pivot = row;
298 }
299 }
300
301 return pivot;
302}
303
304static inline __attribute__((always_inline)) void
305swap_pivot_row(double m[6][7], int32_t col, int32_t pivot) {
306 for (int32_t j = col; j < 7; j++) {
307 double tmp = m[col][j];
308 m[col][j] = m[pivot][j];
309 m[pivot][j] = tmp;
310 }
311}
312
313static inline __attribute__((always_inline)) void
314normalize_pivot_row(double m[6][7], int32_t col, double scale) {
315 for (int32_t j = col; j < 7; j++) {
316 m[col][j] /= scale;
317 }
318}
319
320static inline __attribute__((always_inline)) void
321eliminate_matrix_row(double m[6][7], int32_t col, int32_t row, double f) {
322 for (int32_t j = col; j < 7; j++) {
323 m[row][j] -= f * m[col][j];
324 }
325}
326
327static inline __attribute__((always_inline)) void
328eliminate_pivot_column(double m[6][7], int32_t col) {
329 for (int32_t row = 0; row < 6; row++) {
330 if (row == col) {
331 continue;
332 }
333 double f = m[row][col];
334 eliminate_matrix_row(m, col, row, f);
335 }
336}
337
338static int32_t linear(int32_t a, int32_t b, int32_t c, int64_t *r) {
339 double m[6][7] = {{0}};
340 int32_t ids[2] = {b, c};
341 for (int32_t t = 0; t < 2; t++) {
342 Stone *x = &stones[a], *y = &stones[ids[t]];
343 int64_t dp[3], dv[3];
344 subtract_stone_vectors(x, y, dp, dv);
345 int32_t row = t * 3;
346 build_rock_equations(m, x, y, dp, dv, row);
347 }
348 for (int32_t col = 0; col < 6; col++) {
349 int32_t pivot = col;
350 pivot = select_matrix_pivot(m, col, pivot);
351 if (absolute(m[pivot][col]) < 1e-10) {
352 return 0;
353 }
354 swap_pivot_row(m, col, pivot);
355 double scale = m[col][col];
356 normalize_pivot_row(m, col, scale);
357 eliminate_pivot_column(m, col);
358 }
359 for (int32_t i = 0; i < 6; i++) {
360 double x = m[i][6];
361 if (!(x >= -(double)POSITION && x <= (double)POSITION)) {
362 return 0;
363 }
364 r[i] = (int64_t)(x + (x < 0 ? -0.5 : 0.5));
365 }
366 return 1;
367}
368
369static inline __attribute__((always_inline)) void
370read_hailstone_components(int32_t n, int32_t *small_ref, slice l,
371 size_t *q_ref) {
372 for (int32_t k = 0; k < 6; k++) {
373 spaces(l, q_ref);
374 int64_t v = signed_number(l, q_ref, k < 3 ? POSITION : VELOCITY);
375 if (k < 3) {
376 stones[n].p[k] = v;
377 if (abs64(v) > 1000) {
378 (*small_ref) = 0;
379 }
380 } else {
381 stones[n].v[k - 3] = v;
382 }
383 spaces(l, q_ref);
384 if (k < 5) {
385 literal(l, q_ref, k == 2 ? "@" : ",");
386 }
387 }
388}
389
390static inline __attribute__((always_inline)) int64_t count_future_intersections(
391 int32_t n, int64_t low, int64_t high, int64_t answer, int32_t i) {
392 for (int32_t j = i + 1; j < n; j++) {
393 Stone *a = &stones[i], *b = &stones[j];
394 int64_t dx = b->p[0] - a->p[0], dy = b->p[1] - a->p[1],
395 den = a->v[0] * b->v[1] - a->v[1] * b->v[0],
396 ta = dx * b->v[1] - dy * b->v[0],
397 tb = dx * a->v[1] - dy * a->v[0];
398 if (!den) {
399 answer += parallel(a, b, low, high);
400 continue;
401 }
402 if (den < 0) {
403 den = -den;
404 ta = -ta;
405 tb = -tb;
406 }
407 if (ta < 0 || tb < 0) {
408 continue;
409 }
410 if (bound(a->p[0], a->v[0], ta, den, low, 1) &&
411 bound(a->p[0], a->v[0], ta, den, high, 0) &&
412 bound(a->p[1], a->v[1], ta, den, low, 1) &&
413 bound(a->p[1], a->v[1], ta, den, high, 0)) {
414 answer++;
415 }
416 }
417
418 return answer;
419}
420
421static inline __attribute__((always_inline)) int
422try_third_hailstone(int32_t n, int32_t trials, int64_t rock[6], int32_t a,
423 int32_t b, slice *answer_out) {
424 for (int32_t c = b + 1; c < trials; c++) {
425 if (linear(a, b, c, rock) && verify(n, rock)) {
426 {
427 *answer_out = slice_from_i64(rock[0] + rock[1] + rock[2]);
428 return 1;
429 };
430 }
431 }
432
433 return 0;
434}
435
436static inline __attribute__((always_inline)) int
437try_second_hailstone(int32_t n, int32_t trials, int64_t rock[6], int32_t a,
438 slice *answer_out) {
439 for (int32_t b = a + 1; b < trials; b++) {
440 {
441 slice answer;
442 if (try_third_hailstone(n, trials, rock, a, b, &answer)) {
443 {
444 *answer_out = answer;
445 return 1;
446 };
447 }
448 }
449 }
450
451 return 0;
452}
453
454static slice solve(slice s, int32_t part) {
455 size_t p = 0;
456 int32_t n = 0, small = 1;
457 while (p < s.l) {
458 slice l = line(s, &p);
459 aoc_assert(n < STONES, "more than 512 hailstones");
460 size_t q = 0;
461 read_hailstone_components(n, &small, l, &q);
462 aoc_assert(q == l.l, "trailing hailstone data");
463 n++;
464 }
465 aoc_assert(n >= 2, "need at least two hailstones");
466 if (part == 1) {
467 int64_t low = small ? 7 : INT64_C(200000000000000),
468 high = small ? 27 : INT64_C(400000000000000), answer = 0;
469 for (int32_t i = 0; i < n; i++) {
470 answer = count_future_intersections(n, low, high, answer, i);
471 }
472 return slice_from_i64(answer);
473 }
474 int32_t trials = n < TRIAL_STONES ? n : TRIAL_STONES;
475 int64_t rock[6];
476 for (int32_t a = 0; a < trials; a++) {
477 {
478 slice answer;
479 if (try_second_hailstone(n, trials, rock, a, &answer)) {
480 return answer;
481 }
482 }
483 }
484 aoc_assert(0, "no verified integral rock from first 12 hailstones within "
485 "numeric bounds");
486}
487
488slice part1(slice s) {
489 return solve(s, 1);
490}
491
492slice part2(slice s) {
493 return solve(s, 2);
494}
495
496const 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 hailstones move through enormous coordinates, but part one asks about pairs of paths, not every point in the sky. Locally there are 300 stones, giving 44,850 unordered pairs. Positions range from about 10 trillion to 546 trillion, while velocity components range from −886 to 752. The pair count is small. Analytic intersection tests are the straightforward solution; stepping through nanoseconds or allocating the test area would measure entirely the wrong scale.
First separate two meanings of “meet.” Part one ignores z and asks whether the projected future paths cross. The two stones may reach the crossing at different times. Solve p1 + v1 × t1 = p2 + v2 × t2 in x and y, allowing separate t1 and t2. Require both times to be nonnegative and the crossing to lie inside the inclusive test square. Requiring t1 = t2 would answer a collision question that part one explicitly avoids.
A two-dimensional cross product gives the time fractions directly. With delta = p2 − p1 and determinant D = cross(v1, v2), the numerators are cross(delta, v2) and cross(delta, v1). Normalize D to be positive, then reject negative numerators. There is no need to divide to a rounded intersection coordinate: compare each rational coordinate with the square boundaries by cross-multiplication. The products can exceed 64 bits at these coordinate scales, so the implementation uses wider exact arithmetic for those comparisons.
When D is zero, do not divide. The local data has four parallel projected pairs. Distinct parallel lines never meet, but collinear future rays may overlap inside the square; stationary projections need similar care. The implementation handles those cases by exact interval checks and counts an intersecting pair once. It uses [7, 27] for inputs whose position magnitudes are all at most 1,000, and the story's [2 × 10^14, 4 × 10^14] square otherwise.
Part two changes the question completely. One rock must collide with every stone in three dimensions, with each collision happening at the same time for that rock and that particular stone. Its starting position r and velocity u are six unknowns, plus one unknown time per hailstone. Trying velocity triples even in a guessed range of −1,000 through 1,000 already means over eight billion candidates, before choosing a starting position. The equations, rather than a wider brute-force search, deserve our attention.
For stone i, collision means r + u × t_i = p_i + v_i × t_i. Rearranged, r − p_i is parallel to u − v_i, so their vector cross product is zero. This eliminates time, but expanding still leaves the nonlinear term r cross u. At first it seems we have merely moved the difficulty. Then subtract the equations for two stones: that troublesome term is identical in both and cancels. Aha, the difference is linear in the six rock coordinates and velocity components.
For stones i and j, the resulting equation is r cross (v_j − v_i) + (p_j − p_i) cross u = p_j cross v_j − p_i cross v_i. Each vector equation supplies three scalar equations. Two pairs drawn from three suitably independent stones give a six-by-six system. Some triples are degenerate, so try another triple if the system cannot determine a candidate. The rest of the stones become evidence to check it, rather than extra variables in a massive search.
The implementation uses floating elimination to propose an integral rock, then verifies every collision exactly. For each stone and every axis with nonzero relative velocity, reduce (stone_position − rock_position)/(rock_velocity − stone_velocity) to a rational time. All nontrivial axes must give the same nonnegative time; an axis with zero relative velocity must already have matching positions. Collision times need not be integers. Locally the first triple proposes a valid rock, but its numerical coordinates differ from the rounded integers by as much as 0.125, a good reminder that rounding alone is no proof.
The supported scope is 512 stones, position magnitudes through 10^15, input velocity magnitudes through 1,024 and rock velocity magnitudes through 4,096. At most 220 triples among the first twelve stones are tried; unresolved numerical or nonintegral candidates are explicitly refused. The local verified collision times range from roughly 62 billion to 1.04 trillion nanoseconds, all checked without simulating them. The breakthrough is cancellation: subtracting two hard-looking equations removes the shared nonlinear part, and exact verification turns a numerical proposal into a justified answer.
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.