2019 / Day 12

The N-Body Problem

Read the original puzzle on adventofcode.com ↗

The solution

C11

solution.c

1#include "aoc.h"
2
3/* The local input has four moons and maximum initial coordinate magnitude 14.
4 * POSITION = 100 bounds the input. Each axis evolves independently; its
5 * measured return periods are 286332, 193052, and 102356. PERIOD = 1048576
6 * bounds each search, then their LCM combines them. Compare both position and
7 * velocity with the initial axis state, rather than looking for a repeated
8 * position alone. Part 1 simulates the stated 1000 steps. */
9
10typedef struct {
11    slice s;
12    size_t i;
13} Parser;
14
15static int space(uint8_t c) {
16    return c == ' ' || c == '\t' || c == '\r' || c == '\n';
17}
18
19static void ws(Parser *p) {
20    while (p->i < p->s.l && space(p->s.p[p->i])) {
21        p->i++;
22    }
23}
24
25static void text(Parser *p, const char *s) {
26    size_t n = strlen(s);
27    aoc_assert(n <= p->s.l - p->i && !memcmp(p->s.p + p->i, s, n), "bad input");
28    p->i += n;
29}
30
31static int64_t number(Parser *p, int64_t cap) {
32    int neg = 0;
33    if (p->i < p->s.l && p->s.p[p->i] == '-') {
34        neg = 1;
35        p->i++;
36    }
37    size_t b = p->i;
38    int64_t v = 0;
39    while (p->i < p->s.l && p->s.p[p->i] >= '0' && p->s.p[p->i] <= '9') {
40        int d = p->s.p[p->i++] - '0';
41        aoc_assert(d <= cap && v <= (cap - d) / 10, "integer exceeds cap");
42        v = v * 10 + d;
43    }
44    aoc_assert(p->i > b, "expected integer");
45    return neg ? -v : v;
46}
47
48static void finish(Parser *p) {
49    ws(p);
50    aoc_assert(p->i == p->s.l, "trailing input");
51}
52
53static slice line(Parser *p) {
54    size_t b = p->i;
55    while (p->i < p->s.l && p->s.p[p->i] != '\n') {
56        p->i++;
57    }
58    size_t e = p->i;
59    if (e > b && p->s.p[e - 1] == '\r') {
60        e--;
61    }
62    if (p->i < p->s.l) {
63        p->i++;
64    }
65    return (slice){p->s.p + b, e - b};
66}
67
68enum {
69    MOONS = 4,
70    AXES = 3,
71    POSITION = 100,
72    STATE = 1000000,
73    PERIOD = 1048576,
74    ENERGY_STEPS = 1000
75};
76
77static int64_t initial[MOONS][AXES];
78
79static int64_t absolute(int64_t x) {
80    return x < 0 ? -x : x;
81}
82
83static void load(slice in) {
84    Parser p = {in, 0};
85    for (int i = 0; i < MOONS; i++) {
86        Parser q = {line(&p), 0};
87        text(&q, "<x=");
88        initial[i][0] = number(&q, POSITION);
89        text(&q, ", y=");
90        initial[i][1] = number(&q, POSITION);
91        text(&q, ", z=");
92        initial[i][2] = number(&q, POSITION);
93        text(&q, ">");
94        finish(&q);
95    }
96    finish(&p);
97}
98
99static inline __attribute__((always_inline)) void
100apply_pair_gravity(int64_t *p, int64_t *v, int i) {
101    for (int j = i + 1; j < MOONS; j++) {
102        int sign = (p[j] > p[i]) - (p[j] < p[i]);
103        v[i] += sign;
104        v[j] -= sign;
105    }
106}
107
108static void step(int64_t *p, int64_t *v) {
109    for (int i = 0; i < MOONS; i++) {
110        apply_pair_gravity(p, v, i);
111    }
112    for (int i = 0; i < MOONS; i++) {
113        p[i] += v[i];
114        aoc_assert(absolute(p[i]) <= STATE && absolute(v[i]) <= STATE,
115                   "moon state cap");
116    }
117}
118
119static int64_t gcd(int64_t a, int64_t b) {
120    while (b) {
121        int64_t t = a % b;
122        a = b;
123        b = t;
124    }
125    return a;
126}
127
128static inline __attribute__((always_inline)) void
129initialize_axis_positions(int64_t position[AXES][MOONS], int a) {
130    for (int i = 0; i < MOONS; i++) {
131        position[a][i] = initial[i][a];
132    }
133}
134
135static inline __attribute__((always_inline)) void
136simulate_energy_axis(int64_t position[AXES][MOONS],
137                     int64_t velocity[AXES][MOONS], int a) {
138    for (int t = 0; t < ENERGY_STEPS; t++) {
139        step(position[a], velocity[a]);
140    }
141}
142
143static inline __attribute__((always_inline)) void
144sum_moon_energy(int64_t position[AXES][MOONS], int64_t velocity[AXES][MOONS],
145                int i, int64_t *potential_ref, int64_t *kinetic_ref) {
146    for (int a = 0; a < AXES; a++) {
147        (*potential_ref) += absolute(position[a][i]);
148        (*kinetic_ref) += absolute(velocity[a][i]);
149    }
150}
151
152slice part1(slice in) {
153    load(in);
154    int64_t position[AXES][MOONS], velocity[AXES][MOONS] = {{0}};
155    for (int a = 0; a < AXES; a++) {
156        initialize_axis_positions(position, a);
157        simulate_energy_axis(position, velocity, a);
158    }
159    int64_t energy = 0;
160    for (int i = 0; i < MOONS; i++) {
161        int64_t potential = 0, kinetic = 0;
162        sum_moon_energy(position, velocity, i, &potential, &kinetic);
163        energy += potential * kinetic;
164    }
165    return slice_from_i64(energy);
166}
167
168static inline __attribute__((always_inline)) void
169initialize_period_axis(int a, int64_t p[MOONS]) {
170    for (int i = 0; i < MOONS; i++) {
171        p[i] = initial[i][a];
172    }
173}
174
175static inline __attribute__((always_inline)) int
176axis_has_repeated(int a, int64_t p[MOONS], int64_t v[MOONS], int same) {
177    for (int i = 0; i < MOONS; i++) {
178        same &= p[i] == initial[i][a] && v[i] == 0;
179    }
180
181    return same;
182}
183
184static inline __attribute__((always_inline)) int
185find_axis_period(int a, int64_t p[MOONS], int64_t v[MOONS], int period) {
186    for (int t = 1; t <= PERIOD; t++) {
187        step(p, v);
188        int same = 1;
189        same = axis_has_repeated(a, p, v, same);
190        if (same) {
191            period = t;
192            break;
193        }
194    }
195
196    return period;
197}
198
199slice part2(slice in) {
200    load(in);
201    int64_t result = 1;
202    for (int a = 0; a < AXES; a++) {
203        int64_t p[MOONS], v[MOONS] = {0};
204        initialize_period_axis(a, p);
205        int period = 0;
206        period = find_axis_period(a, p, v, period);
207        aoc_assert(period, "moon period cap");
208        int64_t factor = period / gcd(result, period);
209        aoc_assert(result <= INT64_MAX / factor, "moon LCM overflow");
210        result *= factor;
211    }
212    return slice_from_i64(result);
213}
214
215const 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#endif

The aha moment

Four moons, three coordinates each, and a thousand steps. Part one is pleasantly small: four moons make six unordered pairs, so each step needs eighteen coordinate comparisons for gravity and twelve position updates. Eighteen thousand comparisons for the requested simulation is hardly a reason to optimize. Implement the rules directly and use the story's first few states to check the order of operations.

That order matters. Compute every velocity change from the positions at the beginning of the step, then move all the moons using their new velocities. Updating one moon's position while still calculating gravity for another mixes two different times. For each pair, the velocity changes are equal and opposite; equal coordinates cause no change.

After a thousand steps, calculate each moon's energy by multiplying its own sum of absolute position coordinates by its own sum of absolute velocity coordinates, then add those four products. Multiplying the system-wide position and velocity sums would introduce terms belonging to different moons.

Part two looks like a small extension: keep simulating until a state repeats. The second example should make us hesitate. Just four moons already take more than 4.6 billion steps to return. Storing every full state would create an enormous history, while storing only the initial state would save memory but leave the same time problem. A faster loop is not the breakthrough we need.

Read the gravity rule again, one coordinate at a time. An x velocity changes only because of x positions. No y or z value participates. The same is true independently for the other axes. The apparently three-dimensional system is three separate one-dimensional systems advancing together.

Follow one axis using four positions and four velocities. Find when that complete axis state first returns to its initial state. Repeat for the other axes. The full system returns when all three independent clocks line up, so combine their periods with the least common multiple. If two clocks repeat every six and eight steps, they first agree again at twenty-four, not forty-eight. Simply multiplying periods can overcount shared factors.

Do not compare positions alone. The story shows the first example back at its initial positions after 2,771 steps, but with nonzero velocities; the true return is one step later. The same arrangement moving in a different direction has a different future. Moon identities matter too, so compare each moon with its own initial coordinate.

There is a useful reason we can search for a return to the initial state instead of retaining every earlier state. A complete step is reversible. Subtract the current velocity from the current position to recover the previous positions; those positions determine the gravity change, which can then be subtracted from the current velocity. Every full state has a unique predecessor. Consequently, if a trajectory repeats, it cannot first merge into a cycle after an unrelated transient prefix. A repeated state implies a return to the start.

The local axis periods are 286,332, 193,052, and 102,356. Finding them separately takes 581,740 axis steps, or about 3.49 million pair comparisons. Their least common multiple is about 354 trillion full-system steps. Even at an assumed one million complete steps per second, simulating that return directly would take more than eleven years. Separating the independent coordinates is the difference between a short experiment and waiting for a substantial part of a lifetime.

The input has four moons with initial coordinate magnitudes through fourteen. The implementation accepts exactly four, with initial magnitudes through one hundred, checks evolving positions and velocities against a one-million bound, and allows 1,048,576 steps per axis. Failure to find a return within that allowance is an explicit limitation, not proof that the system never repeats. It also checks the combined period for overflow. The huge answer is obtained by combining three small, observed cycles; we never have to visit the enormous time it names.

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.