2018 / Day 09

Marble Mania

Read the original puzzle on adventofcode.com ↗

The solution

C11

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
45/* 2018 day 9. Marble circle.
46 *
47 * Assumption: after BOOT turns in an ordinary ring, every 23 turns are
48 * one scoring cycle. The cycle consumes TAKE clockwise marbles, scores
49 * the nineteenth, and leaves KEEP marbles at the front plus one block
50 * of SPAN. In that block the 19 new labels and three old labels are
51 * offsets of the cycle base, so only the base and the other 15 labels
52 * are stored, BITS bits each, PACK bytes. The circle is not a list of
53 * every marble, and the 100x game is not stepped one insertion at a
54 * time.
55 *
56 * Players are 1..PLAYERS and the part-one last marble is 0..LAST ("bad
57 * game", "integer exceeds cap", "bad input", "expected integer",
58 * "trailing input" otherwise). The queue refuses "marble queue exceeds
59 * cap" and "empty marble queue".
60 *
61 * The queue holds at most BLOCKS of those blocks; FRONT is only the
62 * live window. That table is the 100x circle, not a node per marble.
63 * estimate reports how many blocks that 100x game needs, and their
64 * packed bytes.
65 *
66 * The real line is 411 players and a last marble of 71170. Part 2 multiplies
67 * that marble by 100. LAST = 71200 admits the part-1 game. The packed blocks
68 * are sized for the hundredfold one. The file is those two integers.
69 */
70enum { PLAYERS = 1024 };
71
72enum { LAST = 71200 };
73
74enum { BLOCKS = 176000, SPAN = 37, PACK = 46 };
75
76enum { BITS = 23, MASK = 8388607 };
77
78enum { FRONT = 128 };
79
80enum { BOOT = 92, RING = BOOT + 1 };
81
82enum { TAKE = 22, KEEP = 6 };
83
84/* 23 turns consume 22 old clockwise marbles, score old[18], and leave
85 * six marbles at the front plus a 37-marble block at the back. In that
86 * block all 19 new labels and three old labels are implied by its base.
87 * Store only the base and 15 remaining labels, each in BITS bits: PACK
88 * bytes. */
89static uint8_t blocks[BLOCKS][PACK];
90static uint32_t front[FRONT];
91static int head, count, bhead, bcount;
92static int64_t scores[PLAYERS];
93
94static void load(slice in, int *players, int *last) {
95    Parser p = {in, 0};
96    *players = (int)number(&p, PLAYERS);
97    text(&p, " players; last marble is worth ");
98    *last = (int)number(&p, LAST);
99    text(&p, " points");
100    finish(&p);
101    aoc_assert(*players > 0 && *last >= 0, "bad game");
102}
103
104#define GET(k)                                                                 \
105    ((uint32_t)(s[(k) * BITS / 8] | ((uint32_t)s[(k) * BITS / 8 + 1] << 8) |   \
106                ((uint32_t)s[(k) * BITS / 8 + 2] << 16) |                      \
107                (((k) * BITS % 8 > 1)                                          \
108                     ? ((uint32_t)s[(k) * BITS / 8 + 3] << 24)                 \
109                     : 0)) >>                                                  \
110         ((k) * BITS % 8) &                                                    \
111     MASK)
112
113static void refill(void) {
114    aoc_assert(bcount, "empty marble queue");
115    const uint8_t *s = blocks[bhead];
116    bhead = (bhead + 1) % BLOCKS;
117    bcount--;
118    head = 0;
119    count = SPAN;
120    uint32_t base = GET(0);
121    front[0] = GET(1);
122    front[1] = base + 1;
123    front[2] = base - 3;
124    front[3] = base + 2;
125    front[4] = GET(2);
126    front[5] = base + 3;
127    front[6] = base - 2;
128    front[7] = base + 4;
129    front[8] = GET(3);
130    front[9] = base + 5;
131    front[10] = base - 1;
132    front[11] = base + 6;
133    front[12] = GET(4);
134    front[13] = base + 7;
135    front[14] = GET(5);
136    front[15] = base + 8;
137    front[16] = GET(6);
138    front[17] = base + 9;
139    front[18] = GET(7);
140    front[19] = base + 10;
141    front[20] = GET(8);
142    front[21] = base + 11;
143    front[22] = GET(9);
144    front[23] = base + 12;
145    front[24] = GET(10);
146    front[25] = base + 13;
147    front[26] = GET(11);
148    front[27] = base + 14;
149    front[28] = GET(12);
150    front[29] = base + 15;
151    front[30] = GET(13);
152    front[31] = base + 16;
153    front[32] = GET(14);
154    front[33] = base + 17;
155    front[34] = GET(15);
156    front[35] = base + 18;
157    front[36] = base + 19;
158}
159
160#undef GET
161
162static inline __attribute__((always_inline)) uint32_t pop(void) {
163    if (!count) {
164        refill();
165    }
166    uint32_t v = front[head];
167    head = (head + 1) & (FRONT - 1);
168    count--;
169    return v;
170}
171
172#define PUT(k, value)                                                          \
173    do {                                                                       \
174        uint32_t v = (value) << ((k) * BITS % 8);                              \
175        s[(k) * BITS / 8] |= (uint8_t)v;                                       \
176        s[(k) * BITS / 8 + 1] |= (uint8_t)(v >> 8);                            \
177        s[(k) * BITS / 8 + 2] |= (uint8_t)(v >> 16);                           \
178        if ((k) * BITS % 8 > 1) {                                              \
179            s[(k) * BITS / 8 + 3] |= (uint8_t)(v >> 24);                       \
180        }                                                                      \
181    } while (0)
182
183static void append(uint32_t base, uint32_t old[TAKE]) {
184    aoc_assert(bcount < BLOCKS, "marble queue exceeds cap");
185    uint8_t *s = blocks[(bhead + bcount) % BLOCKS];
186    bcount++;
187    memset(s, 0, PACK);
188    PUT(0, base);
189    PUT(1, old[0]);
190    PUT(2, old[2]);
191    PUT(3, old[4]);
192    PUT(4, old[6]);
193    PUT(5, old[7]);
194    PUT(6, old[8]);
195    PUT(7, old[9]);
196    PUT(8, old[10]);
197    PUT(9, old[11]);
198    PUT(10, old[12]);
199    PUT(11, old[13]);
200    PUT(12, old[14]);
201    PUT(13, old[15]);
202    PUT(14, old[16]);
203    PUT(15, old[17]);
204}
205
206#undef PUT
207
208static inline __attribute__((always_inline))
209uint32_t retreat_seven_marbles(uint32_t prev[RING], uint32_t cur) {
210    for (int i = 0; i < 7; i++) {
211        cur = prev[cur];
212    }
213
214    return cur;
215}
216
217static inline __attribute__((always_inline)) void
218pop_marble_front(uint32_t old[TAKE]) {
219    for (int i = 0; i < TAKE; i++) {
220        old[i] = pop();
221    }
222}
223
224static inline __attribute__((always_inline)) void
225restore_marble_front(uint32_t prefix[KEEP]) {
226    for (int i = KEEP - 1; i >= 0; i--) {
227        head = (head + FRONT - 1) & (FRONT - 1);
228        front[head] = prefix[i];
229        count++;
230    }
231}
232
233static slice solve(slice in, int hundred) {
234    int players, last;
235    load(in, &players, &last);
236    if (hundred) {
237        last *= 100;
238    }
239    memset(scores, 0, sizeof scores);
240    uint32_t next[RING] = {0}, prev[RING] = {0}, cur = 0;
241    int initial = last < BOOT ? last : BOOT;
242    for (int m = 1; m <= initial; m++) {
243        if (m % 23) {
244            uint32_t a = next[cur], b = next[a];
245            next[a] = (uint32_t)m;
246            prev[m] = a;
247            next[m] = b;
248            prev[b] = (uint32_t)m;
249            cur = (uint32_t)m;
250        } else {
251            cur = retreat_seven_marbles(prev, cur);
252            scores[(m - 1) % players] += m + cur;
253            next[prev[cur]] = next[cur];
254            prev[next[cur]] = prev[cur];
255            cur = next[cur];
256        }
257    }
258    if (last > BOOT) {
259        head = count = bhead = bcount = 0;
260        uint32_t p = next[cur];
261        do {
262            front[count++] = p;
263            p = next[p];
264        } while (p != next[cur]);
265        for (int m = 115; m <= last; m += 23) {
266            uint32_t old[TAKE];
267            pop_marble_front(old);
268            uint32_t base = (uint32_t)m - 23;
269            append(base, old);
270            scores[(m - 1) % players] += m + old[18];
271            /* Restore the six clockwise neighbors before the untouched queue.
272             */
273            uint32_t prefix[KEEP] = {old[19],   base + 20, old[20],
274                                     base + 21, old[21],   base + 22};
275            restore_marble_front(prefix);
276        }
277    }
278    int64_t best = 0;
279    for (int i = 0; i < players; i++) {
280        if (scores[i] > best) {
281            best = scores[i];
282        }
283    }
284    return slice_from_i64(best);
285}
286
287slice part1(slice in) {
288    return solve(in, 0);
289}
290
291slice part2(slice in) {
292    return solve(in, 1);
293}
294
295static slice estimate(slice in) {
296    int players, last;
297    load(in, &players, &last);
298    int64_t marbles = (int64_t)last * 100,
299            active = 1 + marbles - 2 * (marbles / 23),
300            blocks_needed = active / SPAN + 1;
301    char out[64];
302    char *e = aoc_printf("%i %i", out, blocks_needed, PACK * blocks_needed);
303    return slice_from_text(out, (size_t)(e - out));
304}
305
306const struct aoc_method aoc_methods[] = {
307    {"estimate", estimate},
308    {0, 0},
309};

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 marble rules are fussy, but the first useful question is simple: what operations does the circle need? We insert beside the current marble, occasionally move seven places backward, and remove one marble. An array with middle insertions can model the example beautifully, yet every insertion may shift a long suffix. The local game has 411 players and ends at marble 71,170, so that representation can already move a great many more elements than there are turns.

A doubly linked ring matches the operations. Ordinary turns follow two clockwise links and splice in a marble. Every twenty-third turn follows seven backward links, adds the new marble and the removed one to the current player's score, then makes the removed marble's clockwise neighbor current. Marble numbers are unique, consecutive IDs, so two arrays of previous and next IDs can replace separately allocated nodes. Each turn now costs a bounded amount of work.

The first scoring event is the best place to check the rules: marble 23 is not inserted, marble nine is removed, and the score increases by 32. Later insertions begin from the newly chosen current marble. Getting that reference point wrong shifts the entire future circle even if the first score looks right.

Part two multiplies the last marble by one hundred, reaching 7,117,000. A shifting array's roughly quadratic work can grow by ten thousand times. The linked-ring algorithm, however, still needs only about seven million turns with a few link operations each. On a normal machine, that is a good complete solution. The remaining difficulty here comes from this project's fixed eight-MiB Wasm memory limit: two four-byte links for each possible marble would need about 54 MiB.

So the implementation takes a further, storage-driven step. Trace a complete scoring cycle rather than individual insertions: twenty-two ordinary turns, then one removal. View the circle as a clockwise sequence starting just after the current marble. Once a short initial game has established enough room, the same local rearrangement repeats every cycle. It consumes the first twenty-two old entries, scores the nineteenth, leaves six entries at the front, and appends a block of thirty-seven at the back. The untouched middle does not need to move.

This is a reusable transformation, not a claim that the whole growing circle repeats. Most labels in the appended block are predictable from the current cycle number. Nineteen are newly inserted consecutive labels; three more are known labels carried from the previous cycle. Only fifteen old labels and the cycle base need storing. Keeping those sixteen values in 23 bits each encodes thirty-seven marbles in forty-six bytes, while a small front window handles the next local change.

The local hundredfold game ends with 6,498,133 marbles still in the circle. The estimate method translates that into a conservative 175,626 packed blocks, about 7.7 MiB, so we can see why this representation fits before running it. The actual simulation begins with 92 ordinary linked-ring turns, then advances by scoring cycles. Any leftover turns after the last multiple of twenty-three cannot alter scores and need not be materialized.

The supported scope is one through 1,024 players and a part-one last marble from zero through 71,200, including the local 71,170. The packed queue holds at most 176,000 blocks and explicitly refuses overflow. Scores use wide integers. The main puzzle breakthrough is the ring representation; the packed cycle treatment is the extra reasoning needed to keep the same game within this site's memory budget.

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.