2024 / Day 23

LAN Party

Read the original puzzle on adventofcode.com ↗

The solution

C11

solution.c

1#include "aoc.h"
2
3/* The local input is 20280 bytes, 3380 lines, longest line 5. The LAN has 520
4 * named computers and 3380 links (degree 13 at every vertex). NODES = 26*26,
5 * EDGES = 32768 and CLIQUE = 64 bound it. Bitset intersections count
6 * t-containing triangles; pivoted Bron-Kerbosch with cardinality pruning finds
7 * a maximum clique. Keep the lexicographically first password on ties. WORK =
8 * 2000000 pivot word examinations bounds exponential search. */
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
25enum {
26    NODES = 26 * 26,
27    WORDS = (NODES + 63) / 64,
28    EDGES = 32768,
29    CLIQUE = 64,
30    WORK = 2000000
31};
32
33static uint64_t adjacent[NODES][WORDS], ps[CLIQUE + 1][WORDS],
34    xs[CLIQUE + 1][WORDS];
35static uint8_t present[NODES];
36static int32_t path[CLIQUE], best[CLIQUE];
37static int32_t bestn, work;
38
39static int32_t popcount(uint64_t *a) {
40    int32_t n = 0;
41    for (int32_t i = 0; i < WORDS; i++) {
42        n += __builtin_popcountll(a[i]);
43    }
44    return n;
45}
46
47static inline __attribute__((always_inline)) int32_t
48insert_sorted_clique_node(int32_t sorted[CLIQUE], int32_t v, int32_t j) {
49    while (j && sorted[j - 1] > v) {
50        sorted[j] = sorted[j - 1];
51        j--;
52    }
53
54    return j;
55}
56
57static void record(int32_t depth) {
58    int32_t sorted[CLIQUE];
59    memcpy(sorted, path, depth * sizeof *path);
60    for (int32_t i = 1; i < depth; i++) {
61        int32_t v = sorted[i], j = i;
62        j = insert_sorted_clique_node(sorted, v, j);
63        sorted[j] = v;
64    }
65    int32_t better = depth > bestn;
66    if (depth == bestn) {
67        for (int32_t i = 0; i < depth; i++) {
68            if (sorted[i] != best[i]) {
69                better = sorted[i] < best[i];
70                break;
71            }
72        }
73    }
74    if (better) {
75        bestn = depth;
76        memcpy(best, sorted, depth * sizeof *best);
77    }
78}
79
80static inline __attribute__((always_inline)) int32_t
81count_pivot_neighbors(int32_t depth, int32_t u, int32_t score) {
82    for (int32_t j = 0; j < WORDS; j++) {
83        aoc_assert(++work <= WORK,
84                   "LAN clique search exceeds 2000000 pivot words");
85        score += __builtin_popcountll(ps[depth][j] & adjacent[u][j]);
86    }
87
88    return score;
89}
90
91static inline __attribute__((always_inline)) void
92score_clique_pivots(int32_t depth, int32_t *pivot_ref, int32_t *most_ref,
93                    int32_t k, uint64_t *bits_ref) {
94    while ((*bits_ref)) {
95        int32_t u = k * 64 + __builtin_ctzll((*bits_ref));
96        (*bits_ref) &= (*bits_ref) - 1;
97        int32_t score = 0;
98        score = count_pivot_neighbors(depth, u, score);
99        if (score > (*most_ref)) {
100            (*most_ref) = score;
101            (*pivot_ref) = u;
102        }
103    }
104}
105
106static inline __attribute__((always_inline)) void
107intersect_clique_candidates(int32_t depth, int32_t u) {
108    for (int32_t j = 0; j < WORDS; j++) {
109        ps[depth + 1][j] = ps[depth][j] & adjacent[u][j];
110        xs[depth + 1][j] = xs[depth][j] & adjacent[u][j];
111    }
112}
113
114static void clique(int32_t depth);
115
116static inline __attribute__((always_inline)) int
117explore_clique_candidates(int32_t depth, int32_t k, uint64_t *bits_ref) {
118    while ((*bits_ref)) {
119        int32_t u = k * 64 + __builtin_ctzll((*bits_ref));
120        uint64_t bit = UINT64_C(1) << (u % 64);
121        (*bits_ref) &= (*bits_ref) - 1;
122        path[depth] = u;
123        intersect_clique_candidates(depth, u);
124        clique(depth + 1);
125        ps[depth][k] &= ~bit;
126        xs[depth][k] |= bit;
127        if (depth + popcount(ps[depth]) < bestn) {
128            return 1;
129        }
130    }
131
132    return 0;
133}
134
135static void clique(int32_t depth) {
136    int32_t count = popcount(ps[depth]);
137    if (depth + count < bestn) {
138        return;
139    }
140    if (!count) {
141        if (!popcount(xs[depth])) {
142            record(depth);
143        }
144        return;
145    }
146    aoc_assert(depth < CLIQUE, "LAN clique exceeds 64 computers");
147    int32_t pivot = -1, most = -1;
148    for (int32_t k = 0; k < WORDS; k++) {
149        uint64_t bits = ps[depth][k] | xs[depth][k];
150        score_clique_pivots(depth, &pivot, &most, k, &bits);
151    }
152    uint64_t choices[WORDS];
153    for (int32_t j = 0; j < WORDS; j++) {
154        choices[j] = ps[depth][j] & ~adjacent[pivot][j];
155    }
156    for (int32_t k = 0; k < WORDS; k++) {
157        uint64_t bits = choices[k];
158        {
159            if (explore_clique_candidates(depth, k, &bits)) {
160                return;
161            }
162        }
163    }
164}
165
166static int32_t node(slice s, size_t p) {
167    aoc_assert(p + 2 <= s.l && s.p[p] >= 'a' && s.p[p] <= 'z' &&
168                   s.p[p + 1] >= 'a' && s.p[p + 1] <= 'z',
169               "computer names need two lowercase letters");
170    return (s.p[p] - 'a') * 26 + s.p[p + 1] - 'a';
171}
172
173static inline __attribute__((always_inline)) void
174count_named_triangles(int64_t *total_ref, int32_t k, uint64_t *bits_ref) {
175    while ((*bits_ref)) {
176        int32_t c = k * 64 + __builtin_ctzll((*bits_ref));
177        (*bits_ref) &= (*bits_ref) - 1;
178        (*total_ref) += c / 26 == 19;
179    }
180}
181
182static inline __attribute__((always_inline)) int64_t
183intersect_triangle_neighbors(int64_t total, int32_t a, int32_t b) {
184    for (int32_t k = b / 64; k < WORDS; k++) {
185        uint64_t bits = adjacent[a][k] & adjacent[b][k];
186        if (k == b / 64) {
187            bits &= b % 64 == 63 ? 0 : UINT64_MAX << ((b % 64) + 1);
188        }
189        if (a / 26 == 19 || b / 26 == 19) {
190            total += __builtin_popcountll(bits);
191        } else {
192            count_named_triangles(&total, k, &bits);
193        }
194    }
195
196    return total;
197}
198
199static inline __attribute__((always_inline)) void
200visit_triangle_links(int64_t *total_ref, int32_t a, int32_t word,
201                     uint64_t *links_ref) {
202    while ((*links_ref)) {
203        int32_t b = word * 64 + __builtin_ctzll((*links_ref));
204        (*links_ref) &= (*links_ref) - 1;
205        if (b <= a) {
206            continue;
207        }
208        (*total_ref) = intersect_triangle_neighbors((*total_ref), a, b);
209    }
210}
211
212static inline __attribute__((always_inline)) int64_t
213count_triangle_words(int64_t total, int32_t a) {
214    for (int32_t word = a / 64; word < WORDS; word++) {
215        uint64_t links = adjacent[a][word];
216        visit_triangle_links(&total, a, word, &links);
217    }
218
219    return total;
220}
221
222static slice solve(slice s, int32_t part) {
223    memset(adjacent, 0, sizeof adjacent);
224    memset(present, 0, sizeof present);
225    size_t p = 0;
226    int32_t edges = 0;
227    while (p < s.l) {
228        slice l = line(s, &p);
229        aoc_assert(l.l == 5 && l.p[2] == '-', "bad LAN link");
230        aoc_assert(++edges <= EDGES, "more than 32768 LAN links");
231        int32_t a = node(l, 0), b = node(l, 3);
232        aoc_assert(a != b, "LAN self-link");
233        present[a] = present[b] = 1;
234        adjacent[a][b / 64] |= UINT64_C(1) << (b % 64);
235        adjacent[b][a / 64] |= UINT64_C(1) << (a % 64);
236    }
237    aoc_assert(edges, "empty LAN");
238    if (part == 1) {
239        int64_t total = 0;
240        for (int32_t a = 0; a < NODES; a++) {
241            total = count_triangle_words(total, a);
242        }
243        return slice_from_i64(total);
244    }
245    memset(ps, 0, sizeof ps);
246    memset(xs, 0, sizeof xs);
247    bestn = work = 0;
248    for (int32_t u = 0; u < NODES; u++) {
249        if (present[u]) {
250            ps[0][u / 64] |= UINT64_C(1) << (u % 64);
251        }
252    }
253    clique(0);
254    char text[CLIQUE * 3];
255    char *end = text;
256    for (int32_t i = 0; i < bestn; i++) {
257        if (i) {
258            *end++ = ',';
259        }
260        *end++ = 'a' + best[i] / 26;
261        *end++ = 'a' + best[i] % 26;
262    }
263    return slice_from_text(text, end - text);
264}
265
266slice part1(slice s) {
267    return solve(s, 1);
268}
269
270slice part2(slice s) {
271    return solve(s, 2);
272}
273
274const 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 network map invites a familiar mistake: treating “connected” as “reachable somehow.” A LAN party here requires a direct connection between every pair of its computers. A chain of three computers is connected, but it is not one of the triangles requested in part one. Translating that sentence correctly matters more than choosing a graph library.

The local network has 520 computers and 3,380 undirected links. Every computer has exactly 13 neighbors. Trying all triples means 23,299,640 candidates, which is feasible in a tight loop. Looking at the sparse adjacency lists gives an even simpler estimate: each computer has only 78 pairs of neighbors, so there are 40,560 neighbor pairs to check across the graph. A triangle exists when those two neighbors also have an edge.

Impose an alphabetical order a < b < c so each triangle is counted once, then check whether any of its names begins with t. Otherwise a triangle with two t-computers can easily be counted twice. The implementation obtains the third vertices by intersecting the first two vertices' neighbor bitsets, retaining only names after b. There are 11,011 triangles locally before applying the t condition. That makes the story's complaint about too many possible parties quite believable.

Part two asks for the largest group with all pairwise connections: a maximum clique. The t condition has disappeared. Growing one promising triangle greedily is tempting, but an early computer might exclude several computers that form a larger party together. “Cannot add anything else” only proves a group is maximal. It does not prove it is maximum. We need to compare alternatives.

A generic subset search over 520 computers is hopeless, but the measured degree changes the outlook. Any clique containing a chosen computer must lie within that computer and its 13 neighbors. It can therefore have at most 14 members. Even considering all 8,192 subsets of each neighborhood gives about 4.3 million candidate subsets, though checking them independently repeats many edge tests. The input gives us a useful foothold before any advanced algorithm: this huge global search has small local neighborhoods.

Build a clique incrementally and keep only vertices connected to every member already chosen. When we add v, intersect the remaining candidates with v's neighbors. If the current clique has six members and only four candidates remain, it cannot beat a known clique of size eleven, regardless of the edges among those candidates. That optimistic upper bound safely cuts off the branch. Finding a good group early is valuable because it strengthens every later cutoff; the group supplies evidence, not an excuse to stop searching.

The implementation uses the pivoted Bron–Kerbosch search. Besides the current clique and available candidates, it remembers candidates already explored so the same maximal group is not rediscovered in different orders. Choose a pivot connected to many available candidates, and branch only on candidates outside its neighborhood. Why can we skip the others? A maximal extension that omitted the pivot and contained only its neighbors could still add the pivot. Thus every maximal extension must include the pivot itself or a vertex not connected to it. This is a logical reduction of the search, not a guess about who attends the party.

On the local network, this search makes 1,012 recursive calls and 43,263 word examinations while choosing pivots. It finds a unique largest group of 13 computers. The original exponential bound has not vanished for arbitrary graphs, but the sparse input and intersecting candidate sets make this instance small. That distinction is worth keeping: knowing a problem is hard in general should prompt us to inspect this input, not give up on exact search.

Two lowercase letters allow at most 676 computer names, represented by eleven-word neighbor bitsets. The implementation accepts up to 32,768 link records, bounds a clique to 64 members and refuses searches exceeding two million pivot-word examinations. For tied largest groups it returns the alphabetically first password, so equal-size branches remain eligible. Duplicate links do not create extra edges. Once the largest group is established, sorting its names and joining them with commas is the easy part.

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.