2015 / Day 16
Aunt Sue
Read the original puzzle on adventofcode.com ↗
The solution
solution.c
1#include "aoc.h"
2
3#include <stdlib.h>
4#include <string.h>
5
6/* 2015 day 16. Aunt Sue. */
7
8enum { MAXSUE = 640 };
9
10enum { NKEY = 10 };
11
12static const char *keynames[NKEY] = {
13 "children", "cats", "samoyeds", "pomeranians", "akitas",
14 "vizslas", "goldfish", "trees", "cars", "perfumes"};
15
16static int target[NKEY] = {3, 7, 2, 3, 0, 0, 5, 3, 2, 1};
17
18static int g_n;
19static int g_id[MAXSUE];
20static int g_have[MAXSUE][NKEY];
21static int g_val[MAXSUE][NKEY];
22
23static int str_eq(const char *a, const char *b) {
24 while (*a && *a == *b) {
25 a++;
26 b++;
27 }
28 return *a == *b;
29}
30
31static int key_index(const char *name) {
32 int k;
33 for (k = 0; k < NKEY; k++) {
34 if (str_eq(name, keynames[k])) {
35 return k;
36 }
37 }
38 return -1;
39}
40
41static void skip_ws(const uint8_t *p, size_t l, size_t *i) {
42 while (*i < l && (p[*i] == ' ' || p[*i] == '\t' || p[*i] == '\r' ||
43 p[*i] == '\n' || p[*i] == ',')) {
44 (*i)++;
45 }
46}
47
48static int parse_ident(const uint8_t *p, size_t l, size_t *i, char *buf,
49 size_t cap) {
50 size_t n = 0;
51 skip_ws(p, l, i);
52 while (*i < l &&
53 ((p[*i] >= 'a' && p[*i] <= 'z') || (p[*i] >= 'A' && p[*i] <= 'Z'))) {
54 if (n < cap - 1) {
55 buf[n++] = (char)p[*i];
56 }
57 (*i)++;
58 }
59 buf[n] = 0;
60 return n > 0;
61}
62
63static int parse_int_at(const uint8_t *p, size_t l, size_t *i, int *out) {
64 int neg = 0;
65 int32_t v = 0;
66 int saw = 0;
67 skip_ws(p, l, i);
68 if (*i < l && (p[*i] == '-' || p[*i] == '+')) {
69 if (p[*i] == '-') {
70 neg = 1;
71 }
72 (*i)++;
73 }
74 while (*i < l && p[*i] >= '0' && p[*i] <= '9') {
75 aoc_assert(v <= (1000000 - (p[*i] - '0')) / 10, "bad clue");
76 v = v * 10 + (p[*i] - '0');
77 (*i)++;
78 saw = 1;
79 }
80 if (!saw) {
81 return 0;
82 }
83 *out = neg ? -(int)v : (int)v;
84 return 1;
85}
86
87static inline __attribute__((always_inline)) void
88clear_sue_properties(int *s_ref, int *k_ref) {
89 g_id[(*s_ref)] = 0;
90 for ((*k_ref) = 0; (*k_ref) < NKEY; (*k_ref)++) {
91 g_have[(*s_ref)][(*k_ref)] = 0;
92 g_val[(*s_ref)][(*k_ref)] = 0;
93 }
94}
95
96static inline __attribute__((always_inline)) size_t
97skip_sue_whitespace(slice input, size_t j) {
98 while (j < input.l && (input.p[j] == ' ' || input.p[j] == '\t' ||
99 input.p[j] == '\r' || input.p[j] == '\n')) {
100 j++;
101 }
102
103 return j;
104}
105
106static inline __attribute__((always_inline)) size_t
107find_sue_line_end(slice input, size_t lineend) {
108 while (lineend < input.l && input.p[lineend] != '\n') {
109 lineend++;
110 }
111
112 return lineend;
113}
114
115static inline __attribute__((always_inline)) size_t
116read_sue_properties(slice input, size_t i, int n, size_t lineend) {
117 while (i < lineend) {
118 char key[32];
119 if (!parse_ident(input.p, lineend, &i, key, sizeof(key))) {
120 skip_ws(input.p, lineend, &i);
121 if (i >= lineend) {
122 break;
123 }
124 aoc_assert(0, "bad clue");
125 }
126 /* colon */
127 skip_ws(input.p, lineend, &i);
128 aoc_assert(i < lineend && input.p[i] == ':', "bad clue");
129 i++;
130 int val;
131 if (!parse_int_at(input.p, lineend, &i, &val)) {
132 aoc_assert(0, "bad clue");
133 }
134 int ki = key_index(key);
135 aoc_assert(ki >= 0, "unknown clue");
136 aoc_assert(!g_have[n][ki], "duplicate clue");
137 g_have[n][ki] = 1;
138 g_val[n][ki] = val;
139 /* skip comma */
140 skip_ws(input.p, lineend, &i);
141 }
142
143 return i;
144}
145
146static inline __attribute__((always_inline)) void
147count_sue_properties(int n, int *k_ref, int *any_ref) {
148 for ((*k_ref) = 0; (*k_ref) < NKEY; (*k_ref)++) {
149 if (g_have[n][(*k_ref)]) {
150 (*any_ref) = 1;
151 }
152 }
153}
154
155static void load(slice input) {
156 size_t i = 0;
157 int n = 0;
158 /* zero */
159 int s, k;
160 for (s = 0; s < MAXSUE; s++) {
161 clear_sue_properties(&s, &k);
162 }
163 while (i < input.l) {
164 size_t j = i;
165 j = skip_sue_whitespace(input, j);
166 if (j >= input.l) {
167 i = j;
168 break;
169 }
170 i = j;
171 /* Sue */
172 char w[16];
173 if (!parse_ident(input.p, input.l, &i, w, sizeof(w)) ||
174 !str_eq(w, "Sue")) {
175 aoc_assert(0, "bad Sue");
176 }
177 int id;
178 if (!parse_int_at(input.p, input.l, &i, &id)) {
179 aoc_assert(0, "bad Sue");
180 }
181 aoc_assert(i < input.l && input.p[i] == ':', "bad Sue");
182 i++; /* colon */
183 aoc_assert(n < MAXSUE, "too many Sues");
184 /* check duplicate id? not necessary */
185 g_id[n] = id;
186 aoc_assert(id > 0, "bad Sue id");
187 /* parse clues until end of line */
188 size_t lineend = i;
189 lineend = find_sue_line_end(input, lineend);
190 /* loop */
191 i = read_sue_properties(input, i, n, lineend);
192 /* advance i to lineend+newline */
193 i = lineend;
194 if (i < input.l) {
195 i++;
196 }
197 /* ensure at least one clue */
198 int any = 0;
199 count_sue_properties(n, &k, &any);
200 aoc_assert(any, "no clues");
201 n++;
202 }
203 aoc_assert(n >= 1 && n <= MAXSUE, "bad Sue count");
204 g_n = n;
205}
206
207static int match_part1(int idx) {
208 int k;
209 for (k = 0; k < NKEY; k++) {
210 if (g_have[idx][k] && g_val[idx][k] != target[k]) {
211 return 0;
212 }
213 }
214 return 1;
215}
216
217static int match_part2(int idx) {
218 int k;
219 for (k = 0; k < NKEY; k++) {
220 if (!g_have[idx][k]) {
221 continue;
222 }
223 int t = target[k];
224 int v = g_val[idx][k];
225 /* ranges for cats, trees: greater than; pomeranians, goldfish: fewer
226 * than */
227 if (k == 1 || k == 7) { /* cats, trees */
228 if (!(v > t)) {
229 return 0;
230 }
231 } else if (k == 3 || k == 6) { /* pomeranians, goldfish */
232 if (!(v < t)) {
233 return 0;
234 }
235 } else {
236 if (v != t) {
237 return 0;
238 }
239 }
240 }
241 return 1;
242}
243
244static int find_unique(int part2) {
245 int idx;
246 int found = -1;
247 int count = 0;
248 for (idx = 0; idx < g_n; idx++) {
249 int ok = part2 ? match_part2(idx) : match_part1(idx);
250 if (ok) {
251 found = idx;
252 count++;
253 }
254 }
255 aoc_assert(count == 1, "ambiguous Sue");
256 return g_id[found];
257}
258
259slice part1(slice input) {
260 load(input);
261 return slice_from_i64((int64_t)find_unique(0));
262}
263
264slice part2(slice input) {
265 load(input);
266 return slice_from_i64((int64_t)find_unique(1));
267}
268
269static slice estimate(slice input) {
270 load(input);
271 return slice_from_i64((int64_t)g_n);
272}
273
274const struct aoc_method aoc_methods[] = {
275 {"estimate", estimate},
276 {0, 0},
277};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
Five hundred Aunts Sue. The family logistics are formidable; the search is kinder. In the local input, each Sue has exactly three remembered facts, with counts from 0 to 10. At most 1,500 comparisons check them all. We can spend our attention on what the evidence means.
It is tempting to fill a ten-property record with zeroes and overwrite what we know. But wait: do we know that this Sue has no cats, or have we forgotten her cats? The story explicitly distinguishes those cases. A missing fact is unknown. Comparing a fabricated zero with the machine's seven would eliminate her for our own bad memory. Keep the value separate from whether it was supplied.
For part 1, retain a Sue precisely when every fact we know about her agrees with the machine. One contradiction is sufficient to eliminate her; several agreements cannot compensate for it. This is constraint checking, rather than picking the record with the highest number of matches. The story expects one survivor, which is worth verifying before returning an ID.
The thank-you card is almost ready when the machine's small print catches our eye. Its cats reading of seven means strictly more than seven. The exact match we trusted a moment ago now fails! Trees work the same way; pomeranians and goldfish must be strictly fewer than their readings. All other known properties still require equality, and missing properties still impose no condition. We have new instructions for interpreting the same evidence, so every candidate deserves another look.
The search itself does not become harder. Keep the same elimination process and change the comparison attached to four property names. The discovery is in the model of the evidence: unknown, equal, greater, and smaller mean different things even when the records look identical. This implementation accepts at most 640 records, IDs through 1,000,000 and clue magnitudes through 1,000,000, and rejects either zero survivors or multiple survivors. The estimate method returns the record count.
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.