2020 / Day 21

Allergen Assessment

Read the original puzzle on adventofcode.com ↗

The solution

C11

solution.c

1#include "aoc.h"
2
3/* The local menu has 36 foods, 200 ingredients and eight allergens, with a
4 * maximum line length of 545. FOODS = 128, INGREDIENTS = 512, ALLERGENS = 16
5 * and NAME = 32 bound it. An allergen can only occur in the intersection of its
6 * foods. The union of those intersections identifies unsafe ingredients;
7 * singleton elimination gives the unique dangerous list, sorted by allergen. */
8
9static slice line(slice s, size_t *p) {
10    size_t b = *p;
11    while (*p < s.l && s.p[*p] != '\n') {
12        (*p)++;
13    }
14    size_t e = *p;
15    if (*p < s.l) {
16        (*p)++;
17    }
18    if (e > b && s.p[e - 1] == '\r') {
19        e--;
20    }
21    return (slice){s.p + b, e - b};
22}
23
24static void literal(slice s, size_t *p, const char *t) {
25    size_t n = strlen(t);
26    aoc_assert(n <= s.l - *p && memcmp(s.p + *p, t, n) == 0, "bad syntax");
27    *p += n;
28}
29
30enum {
31    FOODS = 128,
32    INGREDIENTS = 512,
33    ALLERGENS = 16,
34    NAME = 32,
35    WORDS = INGREDIENTS / 64,
36    INPUT = 32768
37};
38
39static char ingredient[INGREDIENTS][NAME], allergen[ALLERGENS][NAME];
40static int32_t ni, na, occurs[INGREDIENTS];
41static uint64_t candidates[ALLERGENS][WORDS];
42
43static int32_t word(slice s, size_t *p, char names[][NAME], int32_t *n,
44                    int32_t cap) {
45    size_t b = *p;
46    while (*p < s.l && s.p[*p] >= 'a' && s.p[*p] <= 'z') {
47        (*p)++;
48    }
49    size_t len = *p - b;
50    aoc_assert(len > 0 && len < NAME, "bad food name");
51    for (int32_t i = 0; i < *n; i++) {
52        if (strlen(names[i]) == len && memcmp(names[i], s.p + b, len) == 0) {
53            return i;
54        }
55    }
56    aoc_assert(*n < cap, "too many food names");
57    memcpy(names[*n], s.p + b, len);
58    names[*n][len] = 0;
59    return (*n)++;
60}
61
62static int32_t textcmp(const char *a, const char *b) {
63    for (int32_t i = 0; i < NAME; i++) {
64        if (a[i] != b[i]) {
65            return (uint8_t)a[i] < (uint8_t)b[i] ? -1 : 1;
66        }
67        if (!a[i]) {
68            return 0;
69        }
70    }
71    return 0;
72}
73
74static inline __attribute__((always_inline)) size_t
75read_food_ingredients(slice l, size_t i, uint64_t food[WORDS]) {
76    while (i < l.l && l.p[i] != '(') {
77        int32_t k = word(l, &i, ingredient, &ni, INGREDIENTS);
78        uint64_t bit = 1ull << (k % 64);
79        aoc_assert(!(food[k / 64] & bit), "duplicate ingredient");
80        food[k / 64] |= bit;
81        occurs[k]++;
82        literal(l, &i, " ");
83    }
84
85    return i;
86}
87
88static inline __attribute__((always_inline)) uint32_t
89intersect_allergen_candidates(uint32_t initialized, uint64_t food[WORDS],
90                              int32_t a) {
91    for (int32_t w = 0; w < WORDS; w++) {
92        candidates[a][w] =
93            (initialized & (1u << a)) ? candidates[a][w] & food[w] : food[w];
94    }
95
96    return initialized;
97}
98
99static inline __attribute__((always_inline)) void
100read_food_allergens(uint32_t *initialized_ref, slice l, size_t *i_ref,
101                    uint64_t food[WORDS], uint32_t *seen_ref) {
102    for (;;) {
103        int32_t a = word(l, i_ref, allergen, &na, ALLERGENS);
104        aoc_assert(!((*seen_ref) & (1u << a)), "duplicate allergen");
105        (*seen_ref) |= 1u << a;
106        (*initialized_ref) =
107            intersect_allergen_candidates((*initialized_ref), food, a);
108        (*initialized_ref) |= 1u << a;
109        if ((*i_ref) < l.l && l.p[(*i_ref)] == ')') {
110            (*i_ref)++;
111            break;
112        }
113        literal(l, i_ref, ", ");
114    }
115}
116
117static void parse(slice s) {
118    aoc_assert(s.l <= INPUT, "input too long");
119    ni = na = 0;
120    memset(occurs, 0, sizeof occurs);
121    uint32_t initialized = 0;
122    size_t p = 0;
123    int32_t foods = 0;
124    while (p < s.l) {
125        aoc_assert(++foods <= FOODS, "too many foods");
126        slice l = line(s, &p);
127        size_t i = 0;
128        uint64_t food[WORDS] = {0};
129        i = read_food_ingredients(l, i, food);
130        literal(l, &i, "(contains ");
131        uint32_t seen = 0;
132        read_food_allergens(&initialized, l, &i, food, &seen);
133        aoc_assert(i == l.l, "bad food line");
134    }
135    aoc_assert(foods > 0, "empty menu");
136}
137
138static inline __attribute__((always_inline)) int32_t
139ingredient_is_dangerous(int32_t i, int32_t danger) {
140    for (int32_t a = 0; a < na; a++) {
141        danger |= (candidates[a][i / 64] >> (i % 64)) & 1;
142    }
143
144    return danger;
145}
146
147slice part1(slice s) {
148    parse(s);
149    int32_t total = 0;
150    for (int32_t i = 0; i < ni; i++) {
151        int32_t danger = 0;
152        danger = ingredient_is_dangerous(i, danger);
153        if (!danger) {
154            total += occurs[i];
155        }
156    }
157    return slice_from_i64(total);
158}
159
160static inline __attribute__((always_inline)) void
161count_candidate_bits(int32_t *only_ref, int32_t *count_ref, int32_t w,
162                     uint64_t *bits_ref) {
163    while ((*bits_ref)) {
164        int32_t b = __builtin_ctzll((*bits_ref));
165        (*bits_ref) &= (*bits_ref) - 1;
166        (*only_ref) = w * 64 + b;
167        (*count_ref)++;
168    }
169}
170
171static inline __attribute__((always_inline)) void
172count_available_ingredients(uint64_t used[WORDS], int32_t a, int32_t *only_ref,
173                            int32_t *count_ref) {
174    for (int32_t w = 0; w < WORDS; w++) {
175        uint64_t bits = candidates[a][w] & ~used[w];
176        count_candidate_bits(only_ref, count_ref, w, &bits);
177    }
178}
179
180static inline __attribute__((always_inline)) void
181assign_singleton_allergens(int32_t assigned[ALLERGENS], uint64_t used[WORDS],
182                           int32_t *done_ref, int32_t *changed_ref) {
183    for (int32_t a = 0; a < na; a++) {
184        if (assigned[a] >= 0) {
185            continue;
186        }
187        int32_t only = -1, count = 0;
188        count_available_ingredients(used, a, &only, &count);
189        if (count == 1) {
190            assigned[a] = only;
191            used[only / 64] |= 1ull << (only % 64);
192            (*changed_ref) = 1;
193            (*done_ref)++;
194        }
195    }
196}
197
198static inline __attribute__((always_inline)) int32_t
199insert_allergen_by_name(int32_t order[ALLERGENS], int32_t v, int32_t j) {
200    while (j > 0 && textcmp(allergen[order[j - 1]], allergen[v]) > 0) {
201        order[j] = order[j - 1];
202        j--;
203    }
204
205    return j;
206}
207
208slice part2(slice s) {
209    parse(s);
210    int32_t assigned[ALLERGENS], order[ALLERGENS];
211    uint64_t used[WORDS] = {0};
212    for (int32_t a = 0; a < na; a++) {
213        assigned[a] = -1;
214        order[a] = a;
215    }
216    int32_t done = 0;
217    for (int32_t pass = 0; pass < na && done < na; pass++) {
218        int32_t changed = 0;
219        assign_singleton_allergens(assigned, used, &done, &changed);
220        aoc_assert(changed, "ambiguous or inconsistent allergens");
221    }
222    for (int32_t i = 1; i < na; i++) {
223        int32_t v = order[i], j = i;
224        j = insert_allergen_by_name(order, v, j);
225        order[j] = v;
226    }
227    char out[ALLERGENS * NAME];
228    char *q = out;
229    for (int32_t i = 0; i < na; i++) {
230        if (i) {
231            *q++ = ',';
232        }
233        size_t len = strlen(ingredient[assigned[order[i]]]);
234        memcpy(q, ingredient[assigned[order[i]]], len);
235        q += len;
236    }
237    return slice_from_text(out, (size_t)(q - out));
238}
239
240const 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 raft needs provisions, and we have 36 food labels containing 200 distinct ingredient names and eight allergens. There are 2,272 ingredient appearances altogether, with 43 to 87 ingredients in a food. Trying to assign each allergen an arbitrary ingredient would begin with roughly 200 choices eight times over. Before searching, read the labels' promise very carefully.

A listed allergen must be somewhere in that food. An unlisted allergen might still be there. This is the trap: absence from a label is not evidence of absence from the ingredients. If a food does not mention dairy, we cannot cross its ingredients off the dairy candidate list. The translations and labels are incomplete.

Positive evidence is enough. If two foods both list dairy, the dairy ingredient must appear in both ingredient sets. Intersect them. Repeat for every food that explicitly lists dairy, and do the same independently for the other allergens. The local labels contain 72 allergen mentions; even scanning all 200 ingredients per mention would take just 14,400 membership checks. A problem that sounded like guessing foreign words has become a small set-intersection exercise.

The example makes the deduction feel concrete. Its two dairy-labelled foods share only mxmxvkd. That pins dairy down even though we cannot pronounce the ingredient. We did not need a dictionary, or assume that the first label listed everything present. We used only what the story guarantees.

Part one then offers a welcome shortcut. Take the union of all allergen candidate sets. Any ingredient outside it cannot carry any of the listed allergens. We can count its appearances immediately, before deciding the exact allergen-to-ingredient mapping. Locally the union contains only eight ingredients, leaving 192 safe names. Remember that the answer counts appearances across foods, not distinct names: an ingredient occurring ten times contributes ten.

The original part-two instructions ask us to finish the translation and output ingredient names ordered alphabetically by their allergens. This time knowing which names are potentially dangerous is not enough; we need their exact correspondence.

Our local candidate sets have sizes one, two, two, two, two, three, three, and four. Start with the singleton. Once its ingredient is assigned, remove that ingredient from the other allergens' sets because one ingredient contains at most one allergen. More singletons appear, and the chain finishes in three passes. Aha: the one-to-one constraint turns a local certainty into information for all the other labels.

If day 16's tickets are still fresh in memory, this is the same deduction in different clothing. There, columns intersected field rules. Here, allergen labels intersect ingredient sets. The evidence changes, but maintaining possibilities and propagating forced assignments is the same useful model. Even a search over the eight remaining ingredients would now involve only 8! arrangements; the intersections did the important narrowing before we chose how to finish.

The solver accepts up to 128 foods, 512 ingredients, and 16 allergens, with names shorter than 32 characters; the local longest name has nine. Repeated ingredients or allergens within a single label are rejected. For part two, a stalled deduction is reported as ambiguous or inconsistent instead of choosing an unsupported translation. Finally, sort by allergen names and join their assigned ingredients with commas and no spaces—the ingredient names themselves are not the sort key.

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.