2025 / Day 12

Christmas Tree Farm

Read the original puzzle on adventofcode.com ↗

The solution

C11

solution.c

1#include "aoc.h"
2
3/* The local input is 25095 bytes, 1030 lines, longest line 24. There are six
4 * 3x3 shapes with filled areas 7,6,7,7,7,5, and 1000 regions. Width and height
5 * reach 50, a per-type count reaches 83, and a region requests up to 388
6 * pieces. SHAPES=8, REGIONS=2048, DIMENSION=256 and COUNT=1000000 cover these
7 * measurements. The exact area obstruction rejects 510 personal regions;
8 * placing one present in each separate 3x3 slot proves the other 490 fit. None
9 * requires search. Smaller slot certificates also accept narrow shapes.
10 * Ambiguous regions up to EXACT_CELLS=64 use exact rotations/reflections and a
11 * memoized first-free-cell packing search, including leaving unused cells.
12 * WORK=250000 placement/node visits and MEMO=65536 bound that fallback. Larger
13 * ambiguous regions or an exhausted search are explicitly refused, never
14 * silently called impossible. Part two has no computational puzzle and returns
15 * the empty answer. */
16
17static slice line(slice s, size_t *p) {
18    size_t b = *p;
19    while (*p < s.l && s.p[*p] != '\n') {
20        (*p)++;
21    }
22    size_t e = *p;
23    if (*p < s.l) {
24        (*p)++;
25    }
26    if (e > b && s.p[e - 1] == '\r') {
27        e--;
28    }
29    return (slice){s.p + b, e - b};
30}
31
32static uint64_t number(slice s, size_t *p, uint64_t limit) {
33    aoc_assert(*p < s.l && s.p[*p] >= '0' && s.p[*p] <= '9', "bad number");
34    uint64_t n = 0;
35    while (*p < s.l && s.p[*p] >= '0' && s.p[*p] <= '9') {
36        uint64_t d = s.p[(*p)++] - '0';
37        aoc_assert(d <= limit && n <= (limit - d) / 10, "number out of range");
38        n = n * 10 + d;
39    }
40    return n;
41}
42
43static void literal(slice s, size_t *p, const char *t) {
44    size_t n = strlen(t);
45    aoc_assert(*p <= s.l && n <= s.l - *p && memcmp(s.p + *p, t, n) == 0,
46               "bad syntax");
47    *p += n;
48}
49
50enum {
51    SHAPES = 8,
52    REGIONS = 2048,
53    DIMENSION = 256,
54    COUNT = 1000000,
55    EXACT_CELLS = 64,
56    ORIENTATIONS = 8,
57    PLACEMENTS = 512,
58    COVER = 72,
59    MEMO = 65536,
60    WORK = 250000
61};
62
63typedef struct {
64    uint8_t x[9], y[9], w, h;
65} Orientation;
66
67static Orientation orientations[SHAPES][ORIENTATIONS];
68static int32_t variants[SHAPES], areas[SHAPES], shape_count;
69static uint64_t placements[SHAPES][PLACEMENTS];
70static uint16_t cover[SHAPES][EXACT_CELLS][COVER];
71static uint8_t cover_count[SHAPES][EXACT_CELLS];
72static int32_t remaining[SHAPES];
73
74typedef struct {
75    uint64_t occupied, counts;
76    uint8_t used;
77} Entry;
78
79static Entry memo[MEMO];
80static uint64_t board;
81static uint32_t visits, entries;
82
83static void tick(void) {
84    aoc_assert(++visits <= WORK,
85               "present packing exceeds 250000 placement/node visits");
86}
87
88static void add_shape(int32_t id, slice rows[3]) {
89    int32_t n = 0;
90    int32_t xx[9], yy[9];
91    for (int32_t y = 0; y < 3; y++) {
92        aoc_assert(rows[y].l == 3, "present shapes must be 3 by 3");
93        for (int32_t x = 0; x < 3; x++) {
94            uint8_t c = rows[y].p[x];
95            aoc_assert(c == '#' || c == '.', "bad present shape");
96            if (c == '#') {
97                xx[n] = x;
98                yy[n++] = y;
99            }
100        }
101    }
102    aoc_assert(n > 0, "empty present shape");
103    areas[id] = n;
104    variants[id] = 0;
105    uint16_t masks[ORIENTATIONS];
106    for (int32_t flip = 0; flip < 2; flip++) {
107        for (int32_t rotation = 0; rotation < 4; rotation++) {
108            Orientation o = {0};
109            int32_t minx = 3, miny = 3, maxx = 0, maxy = 0;
110            for (int32_t k = 0; k < n; k++) {
111                int32_t x = flip ? 2 - xx[k] : xx[k], y = yy[k];
112                for (int32_t r = 0; r < rotation; r++) {
113                    int32_t t = x;
114                    x = 2 - y;
115                    y = t;
116                }
117                o.x[k] = (uint8_t)x;
118                o.y[k] = (uint8_t)y;
119                if (x < minx) {
120                    minx = x;
121                }
122                if (y < miny) {
123                    miny = y;
124                }
125            }
126            uint16_t mask = 0;
127            for (int32_t k = 0; k < n; k++) {
128                o.x[k] = (uint8_t)(o.x[k] - minx);
129                o.y[k] = (uint8_t)(o.y[k] - miny);
130                if (o.x[k] > maxx) {
131                    maxx = o.x[k];
132                }
133                if (o.y[k] > maxy) {
134                    maxy = o.y[k];
135                }
136                mask |= (uint16_t)(1u << (o.y[k] * 3 + o.x[k]));
137            }
138            o.w = (uint8_t)(maxx + 1);
139            o.h = (uint8_t)(maxy + 1);
140            int32_t duplicate = 0;
141            for (int32_t k = 0; k < variants[id]; k++) {
142                duplicate |= masks[k] == mask;
143            }
144            if (!duplicate) {
145                masks[variants[id]] = mask;
146                orientations[id][variants[id]++] = o;
147            }
148        }
149    }
150}
151
152static uint64_t counts_key(void) {
153    uint64_t key = 0;
154    for (int32_t i = 0; i < shape_count; i++) {
155        key |= (uint64_t)remaining[i] << (8 * i);
156    }
157    return key;
158}
159
160static uint32_t slot(uint64_t occupied, uint64_t counts) {
161    uint64_t h = occupied ^ (counts + UINT64_C(0x9e3779b97f4a7c15));
162    h ^= h >> 30;
163    h *= UINT64_C(0xbf58476d1ce4e5b9);
164    h ^= h >> 27;
165    uint32_t at = (uint32_t)h & (MEMO - 1);
166    while (memo[at].used &&
167           (memo[at].occupied != occupied || memo[at].counts != counts)) {
168        at = (at + 1) & (MEMO - 1);
169    }
170    return at;
171}
172
173static int32_t pack(uint64_t occupied, int32_t needed) {
174    tick();
175    if (!needed) {
176        return 1;
177    }
178    uint64_t counts = counts_key();
179    uint32_t at = slot(occupied, counts);
180    if (memo[at].used) {
181        return 0;
182    }
183    uint64_t free = board & ~occupied;
184    int32_t cell = __builtin_ctzll(free);
185    for (int32_t i = 0; i < shape_count; i++) {
186        if (!remaining[i]) {
187            continue;
188        }
189        for (int32_t k = 0; k < cover_count[i][cell]; k++) {
190            tick();
191            uint64_t mask = placements[i][cover[i][cell][k]];
192            if (mask & occupied) {
193                continue;
194            }
195            remaining[i]--;
196            int32_t fits = pack(occupied | mask, needed - areas[i]);
197            remaining[i]++;
198            if (fits) {
199                return 1;
200            }
201        }
202    }
203    if (__builtin_popcountll(free) > needed &&
204        pack(occupied | (UINT64_C(1) << cell), needed)) {
205        return 1;
206    }
207    at = slot(occupied, counts);
208    aoc_assert(entries < MEMO * 3 / 4,
209               "present packing memo exceeds 49152 states");
210    memo[at] = (Entry){occupied, counts, 1};
211    entries++;
212    return 0;
213}
214
215static int32_t fits(int32_t w, int32_t h, int64_t filled, int64_t pieces) {
216    /* A narrow row reduces the exact search frontier. */
217    if (w > h) {
218        int32_t t = w;
219        w = h;
220        h = t;
221    }
222    int32_t cells = w * h;
223    if (filled > cells) {
224        return 0;
225    }
226    if (!pieces) {
227        return 1;
228    }
229    for (int32_t sw = 1; sw <= 3; sw++) {
230        for (int32_t sh = 1; sh <= 3; sh++) {
231            if ((int64_t)(w / sw) * (h / sh) < pieces) {
232                continue;
233            }
234            int32_t all = 1;
235            for (int32_t i = 0; i < shape_count; i++) {
236                if (!remaining[i]) {
237                    continue;
238                }
239                int32_t possible = 0;
240                for (int32_t k = 0; k < variants[i]; k++) {
241                    Orientation *o = &orientations[i][k];
242                    possible |= o->w <= sw && o->h <= sh;
243                }
244                all &= possible;
245            }
246            if (all) {
247                return 1;
248            }
249        }
250    }
251    aoc_assert(cells <= EXACT_CELLS,
252               "ambiguous present packing exceeds 64 cells");
253    memset(cover_count, 0, sizeof(cover_count));
254    for (int32_t i = 0; i < shape_count; i++) {
255        int32_t count = 0;
256        for (int32_t k = 0; k < variants[i]; k++) {
257            Orientation *o = &orientations[i][k];
258            for (int32_t y = 0; y + o->h <= h; y++) {
259                for (int32_t x = 0; x + o->w <= w; x++) {
260                    aoc_assert(count < PLACEMENTS,
261                               "more than 512 placements for a present shape");
262                    uint64_t mask = 0;
263                    for (int32_t b = 0; b < areas[i]; b++) {
264                        int32_t cell = (y + o->y[b]) * w + x + o->x[b];
265                        mask |= UINT64_C(1) << cell;
266                        aoc_assert(cover_count[i][cell] < COVER,
267                                   "more than 72 placements covering a cell");
268                        cover[i][cell][cover_count[i][cell]++] =
269                            (uint16_t)count;
270                    }
271                    placements[i][count++] = mask;
272                }
273            }
274        }
275    }
276    board = cells == 64 ? UINT64_MAX : (UINT64_C(1) << cells) - 1;
277    memset(memo, 0, sizeof(memo));
278    visits = entries = 0;
279    return pack(0, (int32_t)filled);
280}
281
282slice part1(slice s) {
283    size_t p = 0;
284    shape_count = 0;
285    int32_t regions = 0, result = 0, reading_regions = 0;
286    while (p < s.l) {
287        slice t = line(s, &p);
288        if (!t.l) {
289            continue;
290        }
291        size_t q = 0;
292        uint64_t first = number(t, &q, DIMENSION);
293        if (q < t.l && t.p[q] == 'x') {
294            reading_regions = 1;
295            aoc_assert(shape_count > 0, "no present shapes");
296            aoc_assert(regions++ < REGIONS, "more than 2048 present regions");
297            int32_t w = (int32_t)first;
298            q++;
299            int32_t h = (int32_t)number(t, &q, DIMENSION);
300            aoc_assert(w > 0 && h > 0, "empty present region");
301            literal(t, &q, ":");
302            int64_t filled = 0, pieces = 0;
303            for (int32_t i = 0; i < shape_count; i++) {
304                literal(t, &q, " ");
305                remaining[i] = (int32_t)number(t, &q, COUNT);
306                pieces += remaining[i];
307                filled += (int64_t)remaining[i] * areas[i];
308            }
309            aoc_assert(q == t.l, "bad present region counts");
310            result += fits(w, h, filled, pieces);
311        } else {
312            aoc_assert(!reading_regions, "shape listed after a present region");
313            aoc_assert(shape_count < SHAPES, "more than eight present shapes");
314            aoc_assert(first == (uint64_t)shape_count,
315                       "present indices must be consecutive from zero");
316            literal(t, &q, ":");
317            aoc_assert(q == t.l, "bad present heading");
318            slice rows[3];
319            for (int32_t y = 0; y < 3; y++) {
320                aoc_assert(p < s.l, "incomplete present shape");
321                rows[y] = line(s, &p);
322            }
323            add_shape(shape_count++, rows);
324        }
325    }
326    aoc_assert(regions > 0, "no present regions");
327    return slice_from_i64(result);
328}
329
330slice part2(slice s) {
331    (void)s;
332    return empty_slice;
333}
334
335const 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

After all those elevators, chutes and teleporters, the final obstacle is getting oddly shaped presents under Christmas trees. Rotations, reflections, interlocking holes, no overlaps: this looks like a serious packing puzzle. The public example even invites us to experiment with arrangements. It is quite reasonable to start sketching an exact search. Before writing one, though, inspect the actual scale and ask whether every case really requires that machinery.

The local input has six shapes, each drawn in a 3-by-3 square, with filled areas 7, 6, 7, 7, 7 and 5. There are 1,000 regions, with both dimensions between 35 and 50. A region requests 120–388 presents, and a single type's count reaches 83. An asymmetric 3-by-3 shape can have eight orientations and 2,304 translations inside a 50-by-50 region: up to 18,432 placements before considering any other present. Multiplying choices for hundreds of pieces is not an appealing first plan.

Start with an obstruction that costs almost nothing. Multiply each requested shape count by its number of filled cells, then add. If the presents need more filled cells than the rectangle contains, they cannot fit. Rotation and clever interlocking cannot change occupied area. This immediately rejects 510 local regions. Some exceed the area by only one cell; that is already a complete proof of impossibility.

It is tempting to reverse that test and call every remaining region possible. Stop there. Empty area is necessary, not sufficient. The public example deliberately demonstrates the gap: its final 12-by-5 region requests seven presents of area seven, only 49 occupied cells in a 60-cell rectangle, and still cannot fit them. Shape matters. An area-only answer would get that example wrong.

Instead, seek a construction that proves a yes just as cheaply as area proved a no. Every local present fits inside its own 3-by-3 square. Divide a W-by-H region into floor(W / 3) × floor(H / 3) separate 3-by-3 slots. If the number of requested presents does not exceed that slot count, assign one present to each slot. They cannot overlap because the slots do not overlap. This arrangement may waste space, but we only need to prove that some arrangement exists.

Now comes the delightful surprise: every one of the 490 local regions that survived the area test also passes the slot construction. None lies between the two bounds. Some use every slot, so this is not an approximate density guess. The full input is decided by two exact certificates, with no packing search at all. The intimidating problem description encouraged us to prepare for a much harder set of cases than the input actually contains.

The two tests should remain separate in our reasoning. Failing the slot construction does not prove a region impossible; the example's two interlocking presents fit in a 4-by-4 region even though it holds only one separate 3-by-3 slot. Passing the area test does not prove a region possible either. Between those answers is an unresolved case. Inspecting the local input showed that the unresolved set was empty, which earns the shortcut for these regions without claiming a universal packing theorem.

The implementation retains exact search for small unresolved boards. Generate the distinct rotations and reflections of each shape, then all placements that fit the board. Represent occupied cells with a bit mask. Choose the first free cell and try each remaining present placement that covers it. Also allow that cell to remain unused when there is spare area; this is packing, so forcing every floor tile to belong to a present would discard valid arrangements. Memoize failed combinations of occupied cells and remaining shape counts. Using counts also avoids trying permutations of identical presents.

Region dimensions are limited to 256, with at most 2,048 regions, eight shapes and one million requested copies per type. Shapes use 3-by-3 drawings; narrower bounding boxes can provide smaller slot constructions too. The unresolved fallback accepts boards of at most 64 cells, at most 512 placements per shape and 72 placements covering a cell per shape. It stops explicitly above 250,000 placement/node visits or 49,152 failed states in its 65,536-slot memo table. Larger unresolved cases are refused, never silently declared impossible. The rectangular board is rotated to put its shorter dimension across the search rows.

There is no computational part two; the other Elves arrive with their stars. The final lesson feels appropriately generous: a good solver does not have to demonstrate the most sophisticated algorithm available. Find a cheap impossibility proof, find a cheap construction, and look at what remains. Sometimes the hard problem disappears between two well-chosen bounds, and Christmas gets decorated on time.

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.