2020 / Day 22
Crab Combat
Read the original puzzle on adventofcode.com ↗
The solution
solution.c
1#include "aoc.h"
2
3/* The local game has two 25-card decks containing distinct labels 1 through 50.
4 * With the packed-deck recurrence it takes 2050098 rounds and 15643 cached
5 * subgames. CARDS = 64, DEPTH = 32, CACHE = 32768 (at most 24576 occupied
6 * entries), and ROUNDS = 4000000 bound the solve. Eight cards fit in each
7 * uint64_t, so drawing shifts eight words instead of moving individual bytes.
8 * Exact Brent cycle detection replaces per-round history tables; only a root
9 * cycle needs replay to recover its first repeated state for scoring. Subgame
10 * memoization compares complete packed keys, so hash collisions cannot change a
11 * winner. Larger games fail at an explicit round, depth, or cache bound. */
12
13static slice line(slice s, size_t *p) {
14 size_t b = *p;
15 while (*p < s.l && s.p[*p] != '\n') {
16 (*p)++;
17 }
18 size_t e = *p;
19 if (*p < s.l) {
20 (*p)++;
21 }
22 if (e > b && s.p[e - 1] == '\r') {
23 e--;
24 }
25 return (slice){s.p + b, e - b};
26}
27
28static uint64_t number(slice s, size_t *p, uint64_t limit) {
29 aoc_assert(*p < s.l && s.p[*p] >= '0' && s.p[*p] <= '9', "bad number");
30 uint64_t n = 0;
31 while (*p < s.l && s.p[*p] >= '0' && s.p[*p] <= '9') {
32 uint64_t digit = s.p[(*p)++] - '0';
33 aoc_assert(digit <= limit && n <= (limit - digit) / 10,
34 "number out of range");
35 n = n * 10 + digit;
36 }
37 return n;
38}
39
40static int32_t equal(slice s, const char *t) {
41 return s.l == strlen(t) && memcmp(s.p, t, s.l) == 0;
42}
43
44enum {
45 CARDS = 64,
46 WORDS = CARDS / 8,
47 KEYWORDS = WORDS + 1,
48 DEPTH = 32,
49 CACHE = 32768,
50 ROUNDS = 4000000,
51 INPUT = 2048
52};
53
54struct deck {
55 uint64_t words[WORDS];
56 int32_t n;
57};
58
59struct key {
60 uint64_t words[KEYWORDS];
61 uint8_t a, b;
62};
63
64struct cached {
65 uint64_t hash;
66 struct key key;
67 uint8_t winner;
68};
69static struct cached cache[CACHE];
70static int32_t rounds, cached;
71
72static int32_t get(const struct deck *d, int32_t i) {
73 return (int32_t)((d->words[i / 8] >> (8 * (i % 8))) & 255);
74}
75
76static void push(struct deck *d, int32_t value) {
77 aoc_assert(d->n < CARDS, "deck overflow");
78 d->words[d->n / 8] |= (uint64_t)value << (8 * (d->n % 8));
79 d->n++;
80}
81
82static int32_t pop(struct deck *d) {
83 int32_t value = get(d, 0);
84 for (int32_t i = 0; i < WORDS - 1; i++) {
85 d->words[i] = (d->words[i] >> 8) | (d->words[i + 1] << 56);
86 }
87 d->words[WORDS - 1] >>= 8;
88 d->n--;
89 return value;
90}
91
92static struct deck prefix(const struct deck *d, int32_t n) {
93 struct deck out = {.n = n};
94 for (int32_t i = 0; i < WORDS; i++) {
95 int32_t left = n - 8 * i;
96 if (left >= 8) {
97 out.words[i] = d->words[i];
98 } else if (left > 0) {
99 out.words[i] = d->words[i] & ((1ull << (8 * left)) - 1);
100 }
101 }
102 return out;
103}
104
105static int32_t makekey(const struct deck *a, const struct deck *b,
106 struct key *key) {
107 key->a = (uint8_t)a->n;
108 key->b = (uint8_t)b->n;
109 int32_t n = 0;
110 for (int32_t i = 0; i < (a->n + 7) / 8; i++) {
111 key->words[n++] = a->words[i];
112 }
113 for (int32_t i = 0; i < (b->n + 7) / 8; i++) {
114 key->words[n++] = b->words[i];
115 }
116 return n;
117}
118
119static uint64_t hashkey(const struct key *key, int32_t n) {
120 uint64_t h = (uint64_t)key->a * 257 + key->b;
121 for (int32_t i = 0; i < n; i++) {
122 h = (h ^ key->words[i]) * 1099511628211ull;
123 }
124 return h;
125}
126
127static int32_t samekey(const struct key *a, const struct key *b, int32_t n) {
128 if (a->a != b->a || a->b != b->b) {
129 return 0;
130 }
131 for (int32_t i = 0; i < n; i++) {
132 if (a->words[i] != b->words[i]) {
133 return 0;
134 }
135 }
136 return 1;
137}
138
139static void copykey(struct key *to, const struct key *from, int32_t n) {
140 to->a = from->a;
141 to->b = from->b;
142 for (int32_t i = 0; i < n; i++) {
143 to->words[i] = from->words[i];
144 }
145}
146
147static int32_t game(struct deck *a, struct deck *b, int32_t recursive,
148 int32_t depth);
149
150static int32_t subgame(struct deck *a, struct deck *b, int32_t depth) {
151 struct key key;
152 int32_t n = makekey(a, b, &key);
153 uint64_t hash = hashkey(&key, n);
154 size_t at = (size_t)(hash & (CACHE - 1));
155 for (size_t probe = 0; probe < CACHE; probe++) {
156 if (!cache[at].key.a) {
157 break;
158 }
159 if (cache[at].hash == hash && samekey(&cache[at].key, &key, n)) {
160 return cache[at].winner;
161 }
162 at = (at + 1) & (CACHE - 1);
163 }
164 int32_t winner = game(a, b, 1, depth);
165 at = (size_t)(hash & (CACHE - 1));
166 for (size_t probe = 0; probe < CACHE; probe++) {
167 if (!cache[at].key.a) {
168 break;
169 }
170 at = (at + 1) & (CACHE - 1);
171 }
172 aoc_assert(++cached <= CACHE * 3 / 4,
173 "combat cache exceeds 24576 subgames");
174 cache[at].hash = hash;
175 copykey(&cache[at].key, &key, n);
176 cache[at].winner = (uint8_t)winner;
177 return winner;
178}
179
180static int32_t same_deck(const struct deck *a, const struct deck *b) {
181 if (a->n != b->n) {
182 return 0;
183 }
184 for (int32_t i = 0; i < (a->n + 7) / 8; i++) {
185 if (a->words[i] != b->words[i]) {
186 return 0;
187 }
188 }
189 return 1;
190}
191
192static int32_t same_game(const struct deck *a, const struct deck *b,
193 const struct deck *aa, const struct deck *bb) {
194 return same_deck(a, aa) && same_deck(b, bb);
195}
196
197static void step(struct deck *a, struct deck *b, int32_t recursive,
198 int32_t depth) {
199 aoc_assert(++rounds <= ROUNDS, "combat exceeds 4000000 rounds");
200 int32_t x = pop(a), y = pop(b), winner = x < y;
201 if (recursive && x <= a->n && y <= b->n) {
202 struct deck aa = prefix(a, x), bb = prefix(b, y);
203 winner = subgame(&aa, &bb, depth + 1);
204 }
205 struct deck *w = winner ? b : a;
206 push(w, winner ? y : x);
207 push(w, winner ? x : y);
208}
209
210static inline __attribute__((always_inline)) void
211advance_cycle_checkpoint(int32_t depth, int32_t length, struct deck *cc_ref,
212 struct deck *dd_ref) {
213 for (int32_t i = 0; i < length; i++) {
214 step(cc_ref, dd_ref, 1, depth);
215 }
216}
217
218static inline __attribute__((always_inline)) int
219locate_repeated_round(struct deck *a, struct deck *b, int32_t depth,
220 struct deck *aa_ref, struct deck *bb_ref,
221 struct deck *cc_ref, struct deck *dd_ref,
222 int32_t *answer_out) {
223 for (int32_t i = 0; i < ROUNDS; i++) {
224 if (same_game(aa_ref, bb_ref, cc_ref, dd_ref)) {
225 *a = (*aa_ref);
226 *b = (*bb_ref);
227 {
228 *answer_out = 0;
229 return 1;
230 };
231 }
232 step(aa_ref, bb_ref, 1, depth);
233 step(cc_ref, dd_ref, 1, depth);
234 }
235
236 return 0;
237}
238
239static int32_t game(struct deck *a, struct deck *b, int32_t recursive,
240 int32_t depth) {
241 aoc_assert(depth < DEPTH, "combat recursion too deep");
242 struct deck initialA = *a, initialB = *b, checkpointA = *a,
243 checkpointB = *b;
244 int32_t power = 1, length = 0;
245 while (a->n && b->n) {
246 if (length == power) {
247 checkpointA = *a;
248 checkpointB = *b;
249 aoc_assert(power <= ROUNDS, "combat cycle exceeds work bound");
250 power *= 2;
251 length = 0;
252 }
253 step(a, b, recursive, depth);
254 length++;
255 if (same_game(a, b, &checkpointA, &checkpointB)) {
256 aoc_assert(recursive, "combat repeats a state");
257 if (depth == 0) {
258 // Brent finds a cycle, then two walkers recover its first
259 // repeated state. Only the root needs the exact winning deck; a
260 // child needs just its winner.
261 struct deck aa = initialA, bb = initialB, cc = initialA,
262 dd = initialB;
263 advance_cycle_checkpoint(depth, length, &cc, &dd);
264 {
265 int32_t answer;
266 if (locate_repeated_round(a, b, depth, &aa, &bb, &cc, &dd,
267 &answer)) {
268 return answer;
269 }
270 }
271 aoc_assert(0, "combat cycle entry exceeds work bound");
272 }
273 return 0;
274 }
275 }
276 return a->n ? 0 : 1;
277}
278
279static slice solve(slice s, int32_t recursive) {
280 aoc_assert(s.l <= INPUT, "input too long");
281 size_t p = 0;
282 aoc_assert(equal(line(s, &p), "Player 1:"), "missing player one");
283 struct deck a = {0}, b = {0};
284 uint8_t seen[CARDS + 1] = {0};
285 while (p < s.l) {
286 slice l = line(s, &p);
287 if (!l.l) {
288 break;
289 }
290 size_t i = 0;
291 int32_t v = (int32_t)number(l, &i, CARDS);
292 aoc_assert(i == l.l && v > 0 && !seen[v] && a.n < CARDS,
293 "bad or duplicate card");
294 seen[v] = 1;
295 push(&a, v);
296 }
297 aoc_assert(equal(line(s, &p), "Player 2:"), "missing player two");
298 while (p < s.l) {
299 slice l = line(s, &p);
300 size_t i = 0;
301 int32_t v = (int32_t)number(l, &i, CARDS);
302 aoc_assert(i == l.l && v > 0 && !seen[v] && b.n < CARDS,
303 "bad or duplicate card");
304 seen[v] = 1;
305 push(&b, v);
306 }
307 aoc_assert(a.n > 0 && b.n > 0 && a.n + b.n <= CARDS, "bad deck sizes");
308 rounds = 0;
309 cached = 0;
310 if (recursive) {
311 memset(cache, 0, sizeof cache);
312 }
313 int32_t winner = game(&a, &b, recursive, 0);
314 struct deck *w = winner ? &b : &a;
315 int64_t score = 0;
316 for (int32_t i = 0; i < w->n; i++) {
317 score += (int64_t)get(w, i) * (w->n - i);
318 }
319 return slice_from_i64(score);
320}
321
322slice part1(slice s) {
323 return solve(s, 0);
324}
325
326slice part2(slice s) {
327 return solve(s, 1);
328}
329
330const 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 crab has twenty-five cards and so do we, with distinct labels one through fifty. Part one is a deterministic queue game: draw the front cards and append them to the winner's deck, winner's card first. The local game lasts 225 rounds. Even moving all fifty card positions every round would mean only 11,250 moves, so a plain simulation is an excellent starting point. We are playing out the rules, not searching for a winning strategy.
The original part-two rules change how a round's winner is decided. After drawing x and y, if both players have enough cards left, copy the next x and y cards into a fresh recursive game. Its winner takes the parent round. Otherwise compare the drawn values as before. The parent decks wait untouched while the child plays, and the winner's drawn card still goes first, even when it has the lower value.
There is also a rule that can end a game before a card is drawn: if the complete ordered pair of decks has appeared earlier in this same game, player one wins immediately. Both decks matter, including their lengths and order. A repeated score, a repeated set of cards, or a state seen in some other game does not qualify. Give every new game its own history.
A recursive simulator with a set of prior states is the clearest first implementation. Recursion does not descend forever: each child uses only cards remaining after the two draws, so its total deck is smaller than its parent's. That does not bound the amount of work tightly, though. Many different rounds can launch the very same smaller game. Watching the simulator repeat those games is where the next useful question appears: what does the parent actually need from its child?
Only the winner. A fresh subgame with the same two starting decks and empty history always has the same result. Cache that winner using both complete decks as the key. Aha: repeated branches can share an answer without sharing their histories. Caching an arbitrary mid-game position as if it were a fresh game would be a different claim; its prior states may affect when the repetition rule fires.
On the local input, a history-set simulator with this cache executes 1,321,618 rounds and stores 15,643 distinct subgame results. The outer game itself has only 589 rounds, and the deepest child is seven levels below it. Those measurements explain why optimizing only the top-level card moves would overlook most of the work.
The repository trades some extra simulation for smaller history storage. It uses Brent's cycle detection: keep a checkpoint state, compare subsequent states with it, and move the checkpoint after intervals that double in length. Equality compares the full decks, so detecting a cycle is exact. A cycling child necessarily awards its game to player one; we need not know where the first repeated state occurred to return that winner.
The root has an extra responsibility because the answer depends on its winning deck. If it cycles, detecting a later point in the cycle is insufficient for scoring. Replay from the initial state with two walkers separated by the detected period; their first meeting recovers the cycle entry, the state at which the story's first-repeat rule would stop the game. This distinction lets children return a winner cheaply while preserving the root's exact score.
With this method the local solve executes 2,050,098 rounds and reuses the same 15,643 cached subgames. The implementation packs eight card labels into each 64-bit word, accepts at most 64 distinct positive labels through 64, limits nested game depth to indices below 32, and permits 4,000,000 total rounds and 24,576 cached results. Full-key comparisons resolve hash collisions. Larger work is explicitly refused; a hash match alone never decides who beats the crab.
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.