2015 / Day 13

Knights of the Dinner Table

Read the original puzzle on adventofcode.com ↗

The solution

C11

solution.c

1#include "aoc.h"
2
3#include <stdlib.h>
4#include <string.h>
5
6/* 2015 day 13. Seating happiness. */
7/* Bonus person (you) included in part2, so 8 input people + 1. */
8
9enum { MAXP = 9 };
10
11enum { NAMELEN = 32 };
12
13static int g_n; /* input people */
14static char g_name[MAXP][NAMELEN];
15static int g_hap[MAXP][MAXP]; /* directed happiness */
16static uint8_t g_have[MAXP][MAXP];
17
18static int str_eq(const char *a, const char *b) {
19    while (*a && *a == *b) {
20        a++;
21        b++;
22    }
23    return *a == *b;
24}
25
26static int person_id(const char *nm, int *nn_out) {
27    int i;
28    int n = *nn_out;
29    for (i = 0; i < n; i++) {
30        if (str_eq(g_name[i], nm)) {
31            return i;
32        }
33    }
34    aoc_assert(n < MAXP, "too many people");
35    memset(g_name[n], 0, NAMELEN);
36    memcpy(g_name[n], nm, strlen(nm));
37    g_name[n][strlen(nm)] = 0;
38    *nn_out = n + 1;
39    return n;
40}
41
42static int read_token(const uint8_t *p, size_t l, size_t *i, char *buf,
43                      size_t cap) {
44    size_t s = *i;
45    size_t e;
46    while (s < l &&
47           (p[s] == ' ' || p[s] == '\t' || p[s] == '\r' || p[s] == '\n')) {
48        s++;
49    }
50    e = s;
51    while (e < l &&
52           !(p[e] == ' ' || p[e] == '\t' || p[e] == '\r' || p[e] == '\n')) {
53        e++;
54    }
55    if (e == s) {
56        return 0;
57    }
58    if (e - s >= cap) {
59        return 0;
60    }
61    memcpy(buf, p + s, e - s);
62    buf[e - s] = 0;
63    /* strip a trailing period from tokens such as "Bob." */
64    if (e > s && buf[e - s - 1] == '.') {
65        buf[e - s - 1] = 0;
66    }
67    *i = e;
68    return 1;
69}
70
71static void skip_ws(const uint8_t *p, size_t l, size_t *i) {
72    while (*i < l &&
73           (p[*i] == ' ' || p[*i] == '\t' || p[*i] == '\r' || p[*i] == '\n')) {
74        (*i)++;
75    }
76}
77
78static int match_lit(const uint8_t *p, size_t l, size_t *i, const char *s) {
79    size_t n = strlen(s);
80    skip_ws(p, l, i);
81    if (*i + n > l) {
82        return 0;
83    }
84    if (memcmp(p + *i, s, n) != 0) {
85        return 0;
86    }
87    *i += n;
88    return 1;
89}
90
91static int parse_int(const uint8_t *p, size_t l, size_t *i, int *out) {
92    int neg = 0;
93    int32_t v = 0;
94    int saw = 0;
95    skip_ws(p, l, i);
96    if (*i < l && (p[*i] == '-' || p[*i] == '+')) {
97        if (p[*i] == '-') {
98            neg = 1;
99        }
100        (*i)++;
101    }
102    while (*i < l && p[*i] >= '0' && p[*i] <= '9') {
103        aoc_assert(v <= (100000 - (p[*i] - '0')) / 10, "bad happiness");
104        v = v * 10 + (p[*i] - '0');
105        (*i)++;
106        saw = 1;
107    }
108    if (!saw) {
109        return 0;
110    }
111    *out = neg ? -(int)v : (int)v;
112    return 1;
113}
114
115static inline __attribute__((always_inline)) size_t skip_line_tail(slice input,
116                                                                   size_t i) {
117    while (i < input.l && input.p[i] != '\n') {
118        i++;
119    }
120
121    return i;
122}
123
124static inline __attribute__((always_inline)) void
125check_guest_connections(int n, int *a_ref, int *b_ref) {
126    for ((*b_ref) = 0; (*b_ref) < n; (*b_ref)++) {
127        if ((*a_ref) != (*b_ref)) {
128            aoc_assert(g_have[(*a_ref)][(*b_ref)], "missing seating");
129        }
130    }
131}
132
133static void load(slice input) {
134    size_t i = 0;
135    int n = 0;
136    int k;
137    memset(g_have, 0, sizeof g_have);
138    memset(g_hap, 0, sizeof g_hap);
139    for (k = 0; k < MAXP; k++) {
140        memset(g_name[k], 0, NAMELEN);
141    }
142
143    while (i < input.l) {
144        char name1[NAMELEN], name2[NAMELEN];
145        char gainword[16];
146        int val, sign, a, b;
147
148        skip_ws(input.p, input.l, &i);
149        if (i >= input.l) {
150            break;
151        }
152        if (!read_token(input.p, input.l, &i, name1, sizeof(name1))) {
153            aoc_assert(0, "bad input");
154        }
155        if (!match_lit(input.p, input.l, &i, "would")) {
156            aoc_assert(0, "bad input");
157        }
158        if (!read_token(input.p, input.l, &i, gainword, sizeof(gainword))) {
159            aoc_assert(0, "bad input");
160        }
161        if (str_eq(gainword, "gain")) {
162            sign = 1;
163        } else if (str_eq(gainword, "lose")) {
164            sign = -1;
165        } else {
166            aoc_assert(0, "bad input");
167        }
168        if (!parse_int(input.p, input.l, &i, &val)) {
169            aoc_assert(0, "bad input");
170        }
171        if (!match_lit(input.p, input.l, &i, "happiness")) {
172            aoc_assert(0, "bad input");
173        }
174        if (!match_lit(input.p, input.l, &i, "units")) {
175            aoc_assert(0, "bad input");
176        }
177        if (!match_lit(input.p, input.l, &i, "by")) {
178            aoc_assert(0, "bad input");
179        }
180        if (!match_lit(input.p, input.l, &i, "sitting")) {
181            aoc_assert(0, "bad input");
182        }
183        if (!match_lit(input.p, input.l, &i, "next")) {
184            aoc_assert(0, "bad input");
185        }
186        if (!match_lit(input.p, input.l, &i, "to")) {
187            aoc_assert(0, "bad input");
188        }
189        if (!read_token(input.p, input.l, &i, name2, sizeof(name2))) {
190            aoc_assert(0, "bad input");
191        }
192        aoc_assert(!str_eq(name1, name2), "self seating");
193        a = person_id(name1, &n);
194        b = person_id(name2, &n);
195        aoc_assert(!g_have[a][b], "duplicate seating");
196        g_hap[a][b] = sign * val;
197        g_have[a][b] = 1;
198        /* consume rest of line */
199        i = skip_line_tail(input, i);
200        if (i < input.l) {
201            i++;
202        }
203    }
204
205    aoc_assert(n >= 2 && n <= 8, "bad people count");
206    int a, b;
207    /* complete directed graph */
208    for (a = 0; a < n; a++) {
209        check_guest_connections(n, &a, &b);
210    }
211    g_n = n;
212}
213
214/* Recursion helpers using globals for current n */
215static int g_m;
216static int g_cur[MAXP];
217static int g_usedmask;
218static int g_best;
219static int g_have_best;
220
221static void dfs_perm(int pos) {
222    int next;
223    if (pos == g_m) {
224        int total = 0;
225        int k;
226        for (k = 0; k < g_m; k++) {
227            int u = g_cur[k];
228            int v = g_cur[(k + 1) % g_m];
229            total += g_hap[u][v] + g_hap[v][u];
230        }
231        if (!g_have_best || total > g_best) {
232            g_best = total;
233            g_have_best = 1;
234        }
235        return;
236    }
237    for (next = 0; next < g_m; next++) {
238        if (!(g_usedmask & (1 << next))) {
239            if (pos == 0 && next != 0) {
240                /* fix person 0 at slot 0: only allow index 0 first */
241                continue;
242            }
243            g_usedmask |= (1 << next);
244            g_cur[pos] = next;
245            dfs_perm(pos + 1);
246            g_usedmask &= ~(1 << next);
247        }
248    }
249}
250
251static int solve_max(int m) {
252    g_m = m;
253    g_usedmask = 0;
254    g_have_best = 0;
255    g_best = 0;
256    /* reserve 0 */
257    g_usedmask |= 1;
258    g_cur[0] = 0;
259    dfs_perm(1);
260    aoc_assert(g_have_best, "no seating");
261    return g_best;
262}
263
264slice part1(slice input) {
265    load(input);
266    return slice_from_i64((int64_t)solve_max(g_n));
267}
268
269slice part2(slice input) {
270    int i;
271    load(input);
272    /* add you as person index g_n with zero happiness both ways */
273    g_n++; /* now MAX? */
274    aoc_assert(g_n <= MAXP, "too many");
275    for (i = 0; i < g_n; i++) {
276        g_hap[i][g_n - 1] = 0;
277        g_hap[g_n - 1][i] = 0;
278        g_have[i][g_n - 1] = 1;
279        g_have[g_n - 1][i] = 1;
280    }
281    g_have[g_n - 1][g_n - 1] = 1;
282    /* complete graph check not needed */
283    return slice_from_i64((int64_t)solve_max(g_n));
284}
285
286static slice estimate(slice input) {
287    load(input);
288    return slice_from_i64((int64_t)g_n);
289}
290
291const struct aoc_method aoc_methods[] = {
292    {"estimate", estimate},
293    {0, 0},
294};

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 family has supplied a remarkably precise account of how much they dislike one another. Where do we begin? With just two people: Alice loses two beside David while David gains 46 beside Alice. Together, that seating choice contributes 44. They need not agree about each other; our total simply includes both feelings. Combine the two directed preferences whenever evaluating a neighboring pair.

The local input has eight guests and 56 directed preferences, with values from -98 to 97. Trying every order means 8! = 40,320 arrangements, already small enough. The circular table gives a free reduction: rotating everyone one seat leaves every neighbor unchanged. Fix one person at the first seat and permute the other seven. Now only 7! = 5,040 arrangements need scoring.

For each arrangement, add the combined preference for every adjacent pair, including the last person beside the first. This closing edge is the difference from day 9's open route. Greedily choosing each person's favorite neighbor is unreliable: choosing one edge consumes a neighbor slot at both ends and constrains everyone else's arrangement. At this scale, checking all arrangements is easier than proving a greedy rule.

Part 2 remembers that we need a chair too. All our relationships score zero, so perhaps the answer stays the same? Try sitting between Alice and David: they are no longer neighbors. We have removed their old contribution. If it was negative, our supposedly neutral presence has made dinner happier. Zero contribution does not mean zero effect.

It is tempting to squeeze ourselves into the best gap in yesterday's winning arrangement. Hang on: that arrangement was chosen with every old edge still present. Fix ourselves at the table and read the other guests in order from our left to our right. Their scored relationships now form an open path. The best circle need not contain the best path, so search again. The extra chair has quietly changed the shape of the optimization.

With nine people and one seat fixed, part 2 has 8! = 40,320 arrangements. Exhaustive search still comfortably fits. The implementation accepts two through eight input guests, requires every directed preference, bounds each preference's magnitude at 100,000, and adds the ninth guest internally. The estimate method reports the input guest count; applying the factorial calculation to that count is what tells us whether this search is affordable.

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.