2020 / Day 20

Jurassic Jigsaw

Read the original puzzle on adventofcode.com ↗

The solution

C11

solution.c

1#include "aoc.h"
2
3/* The local image has 144 tiles, each 10 by 10, and IDs at most 3967. Its
4 * canonical edges occur once (48 outer edges) or twice (264 internal pairs).
5 * TILES = 256, IDCAP = 10000 (IDs below this), and SIDE = 16 bound a square
6 * assembly. Confirm that edge-incidence assumption before greedily matching
7 * oriented edges; no factorial search is needed. Remove borders and mark the
8 * union of sea-monster pixels in all eight image orientations so overlaps are
9 * counted only once. */
10
11static slice line(slice s, size_t *p) {
12    size_t b = *p;
13    while (*p < s.l && s.p[*p] != '\n') {
14        (*p)++;
15    }
16    size_t e = *p;
17    if (*p < s.l) {
18        (*p)++;
19    }
20    if (e > b && s.p[e - 1] == '\r') {
21        e--;
22    }
23    return (slice){s.p + b, e - b};
24}
25
26static uint64_t number(slice s, size_t *p, uint64_t limit) {
27    aoc_assert(*p < s.l && s.p[*p] >= '0' && s.p[*p] <= '9', "bad number");
28    uint64_t n = 0;
29    while (*p < s.l && s.p[*p] >= '0' && s.p[*p] <= '9') {
30        uint64_t digit = s.p[(*p)++] - '0';
31        aoc_assert(digit <= limit && n <= (limit - digit) / 10,
32                   "number out of range");
33        n = n * 10 + digit;
34    }
35    return n;
36}
37
38static void literal(slice s, size_t *p, const char *t) {
39    size_t n = strlen(t);
40    aoc_assert(n <= s.l - *p && memcmp(s.p + *p, t, n) == 0, "bad syntax");
41    *p += n;
42}
43
44enum {
45    TILES = 256,
46    IDCAP = 10000,
47    SIDE = 16,
48    TILE = 10,
49    INNER = 8,
50    IMAGE = SIDE * INNER,
51    EDGE = 1024,
52    INPUT = 32768
53};
54
55static uint8_t tile[TILES][TILE][TILE], image[IMAGE][IMAGE],
56    marks[IMAGE][IMAGE], used[TILES];
57static int32_t ids[TILES], frequency[EDGE], n, side, placed[TILES],
58    orientation[TILES];
59static uint16_t edges[TILES][8][4];
60
61static int32_t reverse(int32_t e) {
62    int32_t r = 0;
63    for (int32_t i = 0; i < TILE; i++) {
64        r = r * 2 + (e & 1);
65        e >>= 1;
66    }
67    return r;
68}
69
70static int32_t canonical(int32_t e) {
71    int32_t r = reverse(e);
72    return e < r ? e : r;
73}
74
75static uint8_t pixel(int32_t t, int32_t o, int32_t y, int32_t x) {
76    if (o & 4) {
77        x = TILE - 1 - x;
78    }
79    for (int32_t i = 0; i < (o & 3); i++) {
80        int32_t tmp = x;
81        x = y;
82        y = TILE - 1 - tmp;
83    }
84    return tile[t][y][x];
85}
86
87static void parse(slice s) {
88    aoc_assert(s.l <= INPUT, "input too long");
89    size_t p = 0;
90    n = 0;
91    memset(frequency, 0, sizeof frequency);
92    while (p < s.l) {
93        slice l = line(s, &p);
94        if (!l.l) {
95            continue;
96        }
97        aoc_assert(n < TILES, "too many tiles");
98        size_t i = 0;
99        literal(l, &i, "Tile ");
100        ids[n] = (int32_t)number(l, &i, IDCAP - 1);
101        literal(l, &i, ":");
102        aoc_assert(i == l.l && ids[n] > 0, "bad tile header");
103        for (int32_t j = 0; j < n; j++) {
104            aoc_assert(ids[j] != ids[n], "duplicate tile ID");
105        }
106        for (int32_t y = 0; y < TILE; y++) {
107            l = line(s, &p);
108            aoc_assert(l.l == TILE, "tile must be 10 by 10");
109            for (int32_t x = 0; x < TILE; x++) {
110                aoc_assert(l.p[x] == '#' || l.p[x] == '.', "bad tile pixel");
111                tile[n][y][x] = l.p[x] == '#';
112            }
113        }
114        for (int32_t o = 0; o < 8; o++) {
115            for (int32_t e = 0; e < 4; e++) {
116                int32_t v = 0;
117                for (int32_t k = 0; k < TILE; k++) {
118                    int32_t y = e == 0   ? 0
119                                : e == 2 ? TILE - 1
120                                         : k,
121                            x = e == 1   ? TILE - 1
122                                : e == 3 ? 0
123                                         : k;
124                    v = v * 2 + pixel(n, o, y, x);
125                }
126                edges[n][o][e] = (uint16_t)v;
127                if (o == 0) {
128                    frequency[canonical(v)]++;
129                }
130            }
131        }
132        n++;
133    }
134    side = 1;
135    while (side <= SIDE && side * side < n) {
136        side++;
137    }
138    aoc_assert(side >= 2 && side <= SIDE && side * side == n,
139               "tile count must be a bounded square");
140    for (int32_t e = 0; e < EDGE; e++) {
141        aoc_assert(frequency[e] <= 2, "edge occurs more than twice");
142    }
143}
144
145static int32_t outer(int32_t t, int32_t o, int32_t edge) {
146    return frequency[canonical(edges[t][o][edge])] == 1;
147}
148
149slice part1(slice s) {
150    parse(s);
151    int32_t corners = 0;
152    int64_t product = 1;
153    for (int32_t t = 0; t < n; t++) {
154        int32_t out = 0;
155        for (int32_t e = 0; e < 4; e++) {
156            out += outer(t, 0, e);
157        }
158        aoc_assert(out <= 2, "tile has too many outer edges");
159        if (out == 2) {
160            aoc_assert(product <= INT64_MAX / ids[t],
161                       "corner product overflow");
162            product *= ids[t];
163            corners++;
164        }
165    }
166    aoc_assert(corners == 4, "expected four corners");
167    return slice_from_i64(product);
168}
169
170static uint8_t im(int32_t o, int32_t y, int32_t x, int32_t size) {
171    if (o & 4) {
172        x = size - 1 - x;
173    }
174    for (int32_t i = 0; i < (o & 3); i++) {
175        int32_t tmp = x;
176        x = y;
177        y = size - 1 - tmp;
178    }
179    return image[y][x];
180}
181
182slice part2(slice s) {
183    parse(s);
184    memset(used, 0, sizeof used);
185    for (int32_t pos = 0; pos < n; pos++) {
186        int32_t row = pos / side, col = pos % side, found = 0;
187        for (int32_t t = 0; t < n && !found; t++) {
188            if (used[t]) {
189                continue;
190            }
191            for (int32_t o = 0; o < 8; o++) {
192                if (outer(t, o, 0) != (row == 0) ||
193                    outer(t, o, 2) != (row == side - 1) ||
194                    outer(t, o, 3) != (col == 0) ||
195                    outer(t, o, 1) != (col == side - 1)) {
196                    continue;
197                }
198                if (row &&
199                    edges[t][o][0] !=
200                        edges[placed[pos - side]][orientation[pos - side]][2]) {
201                    continue;
202                }
203                if (col &&
204                    edges[t][o][3] !=
205                        edges[placed[pos - 1]][orientation[pos - 1]][1]) {
206                    continue;
207                }
208                placed[pos] = t;
209                orientation[pos] = o;
210                used[t] = 1;
211                found = 1;
212                break;
213            }
214        }
215        aoc_assert(found, "edge matching does not determine a square assembly");
216    }
217    int32_t size = side * INNER, total = 0;
218    for (int32_t pos = 0; pos < n; pos++) {
219        for (int32_t y = 0; y < INNER; y++) {
220            for (int32_t x = 0; x < INNER; x++) {
221                uint8_t v = pixel(placed[pos], orientation[pos], y + 1, x + 1);
222                image[pos / side * INNER + y][pos % side * INNER + x] = v;
223                total += v;
224            }
225        }
226    }
227    const char *monster[] = {"                  # ", "#    ##    ##    ###",
228                             " #  #  #  #  #  #   "};
229    int32_t most = 0;
230    for (int32_t o = 0; o < 8; o++) {
231        memset(marks, 0, sizeof marks);
232        for (int32_t y = 0; y + 3 <= size; y++) {
233            for (int32_t x = 0; x + 20 <= size; x++) {
234                int32_t match = 1;
235                for (int32_t dy = 0; dy < 3; dy++) {
236                    for (int32_t dx = 0; dx < 20; dx++) {
237                        if (monster[dy][dx] == '#' &&
238                            !im(o, y + dy, x + dx, size)) {
239                            match = 0;
240                        }
241                    }
242                }
243                if (match) {
244                    for (int32_t dy = 0; dy < 3; dy++) {
245                        for (int32_t dx = 0; dx < 20; dx++) {
246                            if (monster[dy][dx] == '#') {
247                                marks[y + dy][x + dx] = 1;
248                            }
249                        }
250                    }
251                }
252            }
253        }
254        int32_t marked = 0;
255        for (int32_t y = 0; y < size; y++) {
256            for (int32_t x = 0; x < size; x++) {
257                marked += marks[y][x];
258            }
259        }
260        if (marked > most) {
261            most = marked;
262        }
263    }
264    return slice_from_i64(total - most);
265}
266
267const 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

There are 144 tiles, each ten squares across, and every tile may have been rotated or reflected. A 12 by 12 jigsaw with eight orientations per piece suggests 144! × 8^144 arrangements, roughly 6 × 10^379. Trying complete pictures is hopeless. But that estimate assumes the borders tell us nothing, and the story has gone out of its way to give us borders.

Read a border as ten binary digits. Turning a tile over can reverse that sequence, so identify a border by the smaller of its forward and reversed representations. Count these canonical borders across the four original sides of every tile; counting all eight orientations would artificially multiply the evidence.

The local counts are wonderfully revealing. Forty-eight border patterns occur once, and 264 occur twice. No pattern occurs more often. Those numbers match the 48 outside edges and 264 internal joins of a 12 by 12 picture. Four tiles have two unmatched sides, forty have one, and a hundred have none. We have found the corners, boundary pieces, and interior pieces before placing anything.

Wait—the first answer asks only for the product of the corner IDs. Under this measured edge structure, the four tiles with two unmatched sides supply it immediately. Assembling the entire photograph would solve more than part one asks. This is a particularly satisfying shortcut because it comes from looking closely at the input, not from a more elaborate search algorithm.

Part two does need the photograph. Start with a corner oriented so its unmatched edges face up and left. Choosing a different corner merely changes the whole picture's rotation or reflection for this well-formed jigsaw. Fill positions row by row, requiring matching top and left edges and unmatched borders exactly where the outside boundary lies. Every shared edge has only one other occurrence, which makes the neighboring tile highly constrained. The local greedy assembly finishes without backtracking; an independent assembly needed about 40,000 candidate-orientation checks, a very different scale from the original factorial estimate.

This shortcut has an assumption attached. The implementation checks edge incidence, then checks every required join and boundary during placement. It does not claim that arbitrary tiles with repeated borders can be assembled greedily. It refuses patterns occurring more than twice, and refuses an assembly that cannot continue, instead of launching a general jigsaw search.

Now remove each tile's border. Doing this after stitching the full picture and trimming just its outside would leave internal seams behind. Each ten-square tile contributes an eight-square interior, producing a 96 by 96 image.

The monster introduces a different matching rule. Its spaces are wildcards, not required water. Only its fifteen marked pixels must be present. Also, a perfectly assembled image can still be upside down. Check all eight orientations of the whole image. There are 57,904 possible monster placements across those orientations and at most 868,560 required-pixel checks—another search small enough to do directly.

Finally, count covered pixels rather than blindly subtracting fifteen times the number of monsters. Two monsters could overlap, and a shared pixel should be removed from roughness only once. Mark the union of their pixels separately for each orientation and retain the greatest coverage. Locally one orientation has 37 monsters covering 555 distinct pixels; there is no overlap in this particular image, but the counting method does not need that assumption.

The solver accepts square collections of up to 256 tiles, with positive IDs below 10,000; the local maximum ID is 3,967. The main breakthrough is finding structure strong enough to avoid searching arrangements. Once the photograph exists, the final monster hunt is pleasantly small brute force.

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.