2017 / Day 20

Particle Swarm

Read the original puzzle on adventofcode.com ↗

The solution

C11

solution.c

1#include "aoc.h"
2
3/* 2017 day 20. Each component is an integer of magnitude at most
4 * COORD, on a line p=<x,y,z>, v=<x,y,z>, a=<x,y,z>. Twice the
5 * position is the quadratic a*t^2 + (a+2v)*t + 2p, and a collision
6 * is a shared nonnegative integer root of the three coordinates.
7 * "bad input", "expected integer", "integer exceeds cap", "trailing
8 * input", "empty particles", or "too many particles" otherwise. A
9 * pair set that does not fit the event table is "too many collision
10 * events".
11 *
12 * Part 1 does not step the swarm: it compares those polynomials by
13 * the sign each coordinate keeps at large t. Part 2 does not pick a
14 * time horizon. Each pair is solved exactly, and every particle that
15 * meets another at one time is removed together.
16 *
17 * Bounds: NMAX particles and EMAX events. The integer square root
18 * stops at ISQ. estimate is the pair count n*(n-1)/2, the number of
19 * exact solves that search does.
20 *
21 * The real file is 1000 particles. Positions run from -14963 to 14933,
22 * velocities from -483 to 496, accelerations from -38 to 35, and every
23 * acceleration has Manhattan size at least 1. The eventual order is that
24 * acceleration. NMAX = 1024 is the refusal above those 1000.
25 */
26
27enum { NMAX = 1024 };
28
29enum { EMAX = 131072 };
30
31enum { COORD = 1000000 };
32
33enum { ISQ = 10000000 };
34
35typedef struct {
36    slice s;
37    size_t i;
38} Parser;
39
40static int space(uint8_t c) {
41    return c == ' ' || c == '\t' || c == '\r' || c == '\n';
42}
43
44static void ws(Parser *p) {
45    while (p->i < p->s.l && space(p->s.p[p->i])) {
46        p->i++;
47    }
48}
49
50static void text(Parser *p, const char *s) {
51    size_t n = strlen(s);
52    aoc_assert(n <= p->s.l - p->i && !memcmp(p->s.p + p->i, s, n), "bad input");
53    p->i += n;
54}
55
56static int64_t number(Parser *p, int64_t cap) {
57    int neg = 0;
58    int64_t v = 0;
59    if (p->i < p->s.l && (p->s.p[p->i] == '-' || p->s.p[p->i] == '+')) {
60        neg = p->s.p[p->i++] == '-';
61    }
62    size_t start = p->i;
63    while (p->i < p->s.l && p->s.p[p->i] >= '0' && p->s.p[p->i] <= '9') {
64        int d = p->s.p[p->i++] - '0';
65        aoc_assert(v <= (cap - d) / 10 && d <= cap, "integer exceeds cap");
66        v = v * 10 + d;
67    }
68    aoc_assert(p->i > start, "expected integer");
69    return neg ? -v : v;
70}
71
72static void finish(Parser *p) {
73    ws(p);
74    aoc_assert(p->i == p->s.l, "trailing input");
75}
76
77static slice line(Parser *p) {
78    size_t b = p->i;
79    while (p->i < p->s.l && p->s.p[p->i] != '\n') {
80        p->i++;
81    }
82    size_t e = p->i;
83    if (e > b && p->s.p[e - 1] == '\r') {
84        e--;
85    }
86    if (p->i < p->s.l) {
87        p->i++;
88    }
89    return (slice){b ? p->s.p + b : p->s.p, e - b};
90}
91
92typedef struct {
93    int64_t p[3], v[3], a[3];
94} Particle;
95
96typedef struct {
97    int64_t t;
98    int i, j;
99} Event;
100
101static Particle particles[NMAX];
102static Event events[EMAX];
103static int n, ne;
104
105static void triple(Parser *p, int64_t v[3]) {
106    text(p, "<");
107    for (int i = 0; i < 3; i++) {
108        v[i] = number(p, COORD);
109        if (i < 2) {
110            text(p, ",");
111        }
112    }
113    text(p, ">");
114}
115
116static void load(slice in) {
117    Parser p = {in, 0};
118    n = 0;
119    while (p.i < in.l) {
120        aoc_assert(n < NMAX, "too many particles");
121        Parser q = {line(&p), 0};
122        text(&q, "p=");
123        triple(&q, particles[n].p);
124        text(&q, ", v=");
125        triple(&q, particles[n].v);
126        text(&q, ", a=");
127        triple(&q, particles[n++].a);
128        finish(&q);
129    }
130    aoc_assert(n, "empty particles");
131}
132
133slice part1(slice in) {
134    load(in);
135    int best = -1;
136    int64_t key[3] = {0};
137    for (int i = 0; i < n; i++) {
138        int64_t k[3] = {0};
139        for (int j = 0; j < 3; j++) {
140            Particle *p = &particles[i];
141            int64_t a = p->a[j], b = a + 2 * p->v[j], c = 2 * p->p[j];
142            int sign = a   ? (a > 0 ? 1 : -1)
143                       : b ? (b > 0 ? 1 : -1)
144                           : (c >= 0 ? 1 : -1);
145            k[0] += sign * a;
146            k[1] += sign * b;
147            k[2] += sign * c;
148        }
149        if (best < 0 || k[0] < key[0] ||
150            (k[0] == key[0] &&
151             (k[1] < key[1] || (k[1] == key[1] && k[2] < key[2])))) {
152            best = i;
153            memcpy(key, k, sizeof key);
154        }
155    }
156    return slice_from_i64(best);
157}
158
159static int64_t isqrt(int64_t x) {
160    int64_t lo = 0, hi = ISQ;
161    while (lo < hi) {
162        int64_t m = (lo + hi + 1) / 2;
163        if (m * m <= x) {
164            lo = m;
165        } else {
166            hi = m - 1;
167        }
168    }
169    return lo;
170}
171
172/* -1 means every time; otherwise return zero, one or two integer roots. */
173static int roots(int64_t a, int64_t b, int64_t c, int64_t out[2]) {
174    if (!a) {
175        if (!b) {
176            return c ? 0 : -1;
177        }
178        if ((-c) % b) {
179            return 0;
180        }
181        int64_t t = -c / b;
182        if (t < 0) {
183            return 0;
184        }
185        out[0] = t;
186        return 1;
187    }
188    int64_t disc = b * b - 4 * a * c;
189    if (disc < 0) {
190        return 0;
191    }
192    int64_t s = isqrt(disc);
193    if (s * s != disc) {
194        return 0;
195    }
196    int nroot = 0;
197    for (int sign = -1; sign <= 1; sign += 2) {
198        int64_t v = -b + sign * s;
199        if (v % (2 * a) == 0) {
200            int64_t t = v / (2 * a);
201            if (t >= 0 && (!nroot || out[0] != t)) {
202                out[nroot++] = t;
203            }
204        }
205    }
206    return nroot;
207}
208
209static int compare(const void *a, const void *b) {
210    int64_t x = ((const Event *)a)->t, y = ((const Event *)b)->t;
211    return (x > y) - (x < y);
212}
213
214slice part2(slice in) {
215    load(in);
216    ne = 0;
217    for (int i = 0; i < n; i++) {
218        for (int j = i + 1; j < n; j++) {
219            int count = -1;
220            int64_t times[2] = {0};
221            for (int k = 0; k < 3; k++) {
222                Particle *p = &particles[i], *q = &particles[j];
223                int64_t a = p->a[k] - q->a[k], b = a + 2 * (p->v[k] - q->v[k]),
224                        c = 2 * (p->p[k] - q->p[k]), r[2];
225                int nr = roots(a, b, c, r);
226                if (nr < 0) {
227                    continue;
228                }
229                if (count < 0) {
230                    count = nr;
231                    memcpy(times, r, (size_t)nr * sizeof *r);
232                } else {
233                    int out = 0;
234                    for (int t = 0; t < count; t++) {
235                        for (int s = 0; s < nr; s++) {
236                            if (times[t] == r[s]) {
237                                times[out++] = times[t];
238                                break;
239                            }
240                        }
241                    }
242                    count = out;
243                }
244                if (!count) {
245                    break;
246                }
247            }
248            if (count < 0) {
249                count = 1;
250                times[0] = 0;
251            }
252            for (int k = 0; k < count; k++) {
253                aoc_assert(ne < EMAX, "too many collision events");
254                events[ne++] = (Event){times[k], i, j};
255            }
256        }
257    }
258    qsort(events, (size_t)ne, sizeof events[0], compare);
259    uint8_t alive[NMAX], dead[NMAX];
260    memset(alive, 1, (size_t)n);
261    int left = n;
262    for (int i = 0; i < ne;) {
263        int j = i;
264        memset(dead, 0, (size_t)n);
265        while (j < ne && events[j].t == events[i].t) {
266            Event e = events[j++];
267            if (alive[e.i] && alive[e.j]) {
268                dead[e.i] = dead[e.j] = 1;
269            }
270        }
271        for (int k = 0; k < n; k++) {
272            if (dead[k]) {
273                alive[k] = 0;
274                left--;
275            }
276        }
277        i = j;
278    }
279    return slice_from_i64(left);
280}
281
282static slice estimate(slice in) {
283    load(in);
284    return slice_from_i64((int64_t)n * (n - 1) / 2);
285}
286
287const struct aoc_method aoc_methods[] = {
288    {"estimate", estimate},
289    {0, 0},
290};

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#endif

The aha moment

The GPU asks us to simulate fewer particles, but its first question is about the long term. How long is long enough? The local input has 1,000 particles, positions around ±15,000, velocities around ±500, and accelerations from -38 through 35. Running a thousand ticks would be easy. Watching the same winner for a while would be reassuring. Neither observation, by itself, proves that a slower crossover is not still coming.

Look at one coordinate. Velocity changes before position, so after t ticks the position is p + v × t + a × t × (t + 1) / 2. The triangular number matters: using t × (t - 1) / 2 would model the opposite update order. Once we have this formula, the infinite future becomes a comparison of a few coefficients.

Acceleration controls the quadratic growth, so the smallest Manhattan acceleration is the first promising filter. In the local swarm, two particles tie at the minimum value of one. Bummer: stopping at the first minimum would leave the important tie unresolved. Comparing speed magnitudes next is also unsafe. Velocity opposing the eventual direction of travel reduces distance for a long time; the same speed pointing outward increases it.

For each coordinate, determine its eventual sign from the first nonzero item among acceleration, velocity, and position. Multiply its position polynomial by that sign, then sum the three coordinates. This removes the absolute values correctly for sufficiently large t. Twice the eventual Manhattan distance has coefficients A, B, C for t², t, and one. Compare A first, then B if tied, then C. A smaller leading unequal coefficient wins eventually, however messy the early motion was. We have answered the long-term question without choosing an arbitrary final tick.

Part two changes the question from distance to meetings. A straightforward experiment would update all surviving particles, group them by position, and remove groups of size two or more. That is useful for checking the first few collisions. But “nothing collided in the last hundred ticks” has the same weakness as “the winner has not changed”: it is an observation, not a stopping proof.

Instead, subtract two particles' position formulas. A collision requires the resulting quadratic to be zero on all three axes at the same nonnegative integer time. Solve each axis and intersect its possible times. A coordinate that agrees forever imposes no restriction; one that never agrees eliminates the pair. Fractional roots do not count, even if the particles pass through one another between ticks. Integer arithmetic and an exact square-root check avoid deciding near-equality with floating point.

There are only 1,000 × 999 / 2 = 499,500 pairs. That is a manageable exact search, independent of how far into the future a collision might occur. The local input produces 1,675 potential pair events, all between ticks ten and thirty-nine. Now that final tick is established by solving the trajectories, rather than guessed from a quiet simulation.

Process those events in time order, ignoring pairs whose members died earlier. All deaths at one time must be collected before removing anyone: three particles meeting together must all disappear, not leave the third alive because the first pair was erased too soon. The story's example sets up exactly that trap, followed by a fourth particle arriving one tick later and surviving.

The implementation accepts up to 1,024 particles with every position, velocity, and acceleration component within ±1,000,000, and stores at most 131,072 collision events. Its bounded integer square-root search covers the discriminants implied by those component limits. Exceeding the event table is an explicit refusal. The estimate method reports the pair count, which is the useful measure of the exact search we are about to undertake.

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.