2022 / Day 13

Distress Signal

Read the original puzzle on adventofcode.com ↗

The solution

C11

solution.c

1#include "aoc.h"
2
3/* The local input is 22270 bytes, 449 lines, longest line 207 and nesting
4 * depth 4. There are 300 packets, 6555 integers, longest line 207 and nesting
5 * depth 4. PACKETS = 1024, NODES = 65536, DEPTH = 64 and WORK = 4000000 bound
6 * parsing and comparisons. Compare lists recursively, viewing an integer as a
7 * singleton list without allocating a replacement. Equal packets keep input
8 * order, with divider identity preserved. */
9
10static slice line(slice s, size_t *p) {
11    size_t b = *p;
12    while (*p < s.l && s.p[*p] != '\n') {
13        (*p)++;
14    }
15    size_t e = *p;
16    if (*p < s.l) {
17        (*p)++;
18    }
19    if (e > b && s.p[e - 1] == '\r') {
20        e--;
21    }
22    return (slice){s.p + b, e - b};
23}
24
25static uint64_t number(slice s, size_t *p, uint64_t limit) {
26    aoc_assert(*p < s.l && s.p[*p] >= '0' && s.p[*p] <= '9', "bad number");
27    uint64_t n = 0;
28    while (*p < s.l && s.p[*p] >= '0' && s.p[*p] <= '9') {
29        uint64_t d = s.p[(*p)++] - '0';
30        aoc_assert(d <= limit && n <= (limit - d) / 10, "number out of range");
31        n = n * 10 + d;
32    }
33    return n;
34}
35
36static void literal(slice s, size_t *p, const char *t) {
37    size_t n = strlen(t);
38    aoc_assert(*p <= s.l && n <= s.l - *p && memcmp(s.p + *p, t, n) == 0,
39               "bad syntax");
40    *p += n;
41}
42
43enum {
44    PACKETS = 1024,
45    NODES = 65536,
46    DEPTH = 64,
47    WORK = 4000000,
48    VALUE = 1000000
49};
50
51typedef struct {
52    int32_t child, next, value;
53} Node;
54
55static Node nodes[NODES];
56static int32_t roots[PACKETS], order[PACKETS];
57static int32_t nn, np, work;
58
59static int32_t parse_node(slice s, size_t *p, int32_t depth) {
60    aoc_assert(depth < DEPTH, "packet nesting exceeds 64");
61    aoc_assert(nn < NODES, "packet storage exceeds 65536 nodes");
62    int32_t id = nn++;
63    nodes[id] = (Node){-1, -1, -1};
64    if (*p < s.l && s.p[*p] == '[') {
65        (*p)++;
66        int32_t prev = -1;
67        if (*p < s.l && s.p[*p] != ']') {
68            while (1) {
69                int32_t child = parse_node(s, p, depth + 1);
70                if (prev < 0) {
71                    nodes[id].child = child;
72                } else {
73                    nodes[prev].next = child;
74                }
75                prev = child;
76                if (*p < s.l && s.p[*p] == ',') {
77                    (*p)++;
78                    continue;
79                }
80                break;
81            }
82        }
83        literal(s, p, "]");
84    } else {
85        nodes[id].value = (int32_t)number(s, p, VALUE);
86    }
87    return id;
88}
89
90static int32_t compare(int32_t a, int32_t b, int32_t depth) {
91    aoc_assert(depth < DEPTH, "packet comparison nesting exceeds 64");
92    aoc_assert(++work <= WORK, "packet comparison exceeds 4000000 node pairs");
93    if (nodes[a].value >= 0 && nodes[b].value >= 0) {
94        return (nodes[a].value > nodes[b].value) -
95               (nodes[a].value < nodes[b].value);
96    }
97    int32_t x = nodes[a].value >= 0 ? a : nodes[a].child,
98            y = nodes[b].value >= 0 ? b : nodes[b].child;
99    while (x >= 0 && y >= 0) {
100        int32_t c = compare(x, y, depth + 1);
101        if (c) {
102            return c;
103        }
104        x = nodes[a].value >= 0 ? -1 : nodes[x].next;
105        y = nodes[b].value >= 0 ? -1 : nodes[y].next;
106    }
107    return (x >= 0) - (y >= 0);
108}
109
110static int cmp(const void *a, const void *b) {
111    int32_t x = *(const int32_t *)a, y = *(const int32_t *)b,
112            c = compare(roots[x], roots[y], 0);
113    return c ? c : (x > y) - (x < y);
114}
115
116static slice solve(slice s, int32_t part) {
117    nn = np = work = 0;
118    size_t p = 0;
119    while (p < s.l) {
120        slice l = line(s, &p);
121        if (!l.l) {
122            continue;
123        }
124        aoc_assert(np < PACKETS - 2, "too many packets");
125        size_t q = 0;
126        roots[np++] = parse_node(l, &q, 0);
127        aoc_assert(q == l.l, "bad packet syntax");
128    }
129    aoc_assert(np > 0 && np % 2 == 0, "packets must form pairs");
130    if (part == 1) {
131        int32_t sum = 0;
132        for (int32_t i = 0; i < np; i += 2) {
133            if (compare(roots[i], roots[i + 1], 0) < 0) {
134                sum += i / 2 + 1;
135            }
136        }
137        return slice_from_i64(sum);
138    }
139    int32_t first = np;
140    const char *divider[2] = {"[[2]]", "[[6]]"};
141    for (int32_t i = 0; i < 2; i++) {
142        size_t q = 0;
143        roots[np++] = parse_node((slice){(uint8_t *)divider[i], 5}, &q, 0);
144    }
145    for (int32_t i = 0; i < np; i++) {
146        order[i] = i;
147    }
148    qsort(order, (size_t)np, sizeof *order, cmp);
149    int32_t product = 1;
150    for (int32_t i = 0; i < np; i++) {
151        if (order[i] >= first) {
152            product *= i + 1;
153        }
154    }
155    return slice_from_i64(product);
156}
157
158slice part1(slice s) {
159    return solve(s, 1);
160}
161
162slice part2(slice s) {
163    return solve(s, 2);
164}
165
166const 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

The distress signal has 300 packets, paired into 150 comparisons. Together they contain 6,555 integers from zero through ten, and their lists nest at most four levels deep. Parsing and comparing these structures is comfortably small work. The challenge is preserving the meaning of the brackets, not finding a faster sorting algorithm.

Text comparison is tempting because the input already looks sortable. It fails immediately on integers such as 2 and 10, and brackets introduce ordering rules that have nothing to do with character codes. Flattening the integers also loses information: an empty list is smaller than a nonempty list, even if removing brackets would erase that distinction entirely. Parse lists as lists and numbers as numbers.

The comparison needs three possible results: smaller, equal, or greater. For two integers, compare their values. For two lists, compare corresponding elements from left to right and return the first unequal result. Only if all shared elements compare equal does list length decide: the list that runs out first is smaller. Equal nested elements mean “continue with the next sibling,” not “the entire packet is ordered.” That distinction is the heart of the recursion.

For a mixed comparison, view the integer as a one-element list. We need not actually allocate a new list or modify the parsed packet. Treat the integer as an iterator that yields itself once, while an ordinary list yields its children. This lets the same list logic handle both cases. It also reveals a subtle consequence: [2], [[2]], and [[[2]]] compare equal even though their structures differ.

Part one now compares each pair and adds its one-based pair number only when the left packet is strictly smaller. On the local input, those 150 top-level comparisons inspect just 533 node pairs: most decisions occur near the beginning, without traversing whole packets. An equal comparison contributes nothing.

Part two asks us to insert [[2]] and [[6]], sort everything, and multiply their positions. Sorting 302 packets is a fine solution; its rough comparison scale is only a few thousand. Preserve the identity of the two packets we inserted, though. Searching for any packet that compares equal to a divider could pick an original packet instead. This implementation breaks ties by original position, so original packets precede the appended dividers when equal.

There is an optional smaller observation: the answer needs two ranks, not the entire sorted sequence. With that tie convention, the first divider's rank is one plus the number of original packets comparing at most [[2]]. The second's rank is two plus the number comparing at most [[6]], because the first divider also precedes it. That takes 600 top-level comparisons here, inspecting 2,080 node pairs. Neither approach needs sophisticated machinery; the comparator is the part worth getting right.

The implementation retains the straightforward sort. It allows 1,022 input packets plus the two dividers, 65,536 parsed nodes, nesting and comparison recursion below depth 64, and integer values through one million. Comparison work is capped at four million node pairs. Locally there are 10,492 parsed nodes before adding dividers. The satisfying result is that one faithful comparison rule solves both the pair question and the global ordering question.

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.