2017 / Day 21

Fractal Art

Read the original puzzle on adventofcode.com ↗

The solution

C11

solution.c

1#include "aoc.h"
2
3/* 2017 day 21. Three rounds turn one aligned 3x3 into nine aligned
4 * 3x3 tiles (3 to 4 to 6 to 9), and tiles do not interact, so the
5 * picture is a count of the 512 patterns rather than a grid. A
6 * three-round transition is cached only for a pattern that appears.
7 * Leftover rounds are applied to each surviving pattern and summed.
8 * The start is the story's .#./..#/###.
9 *
10 * A rule is 2x2 => 3x3 or 3x3 => 4x4. Rotations and reflections of
11 * the input share that output; the output is stored as written.
12 * "bad pattern size", "short pattern", "bad pixel", "conflicting
13 * rules", "empty rules", or "too many rules" otherwise. A pattern
14 * the expand needs and does not have is "missing enhancement rule".
15 *
16 * Bounds: PAT2, PAT3, and RULES = PAT2 + PAT3. One pattern's
17 * three-round image fits in GRID (CELLS). The histogram stays PAT3
18 * wide, so ROUNDS2 never builds the full picture.
19 *
20 * The real file is 108 rules: 6 of size 2 and 102 of size 3. A 2-rule writes a
21 * 3-pattern, so three rounds replace one cell by nine and the count can stay
22 * on the 512 patterns of a 3-square. The grown image is never stored.
23 */
24
25enum { PAT2 = 16, PAT3 = 512, RULES = PAT2 + PAT3 };
26
27enum { GRID = 9, CELLS = GRID * GRID };
28
29enum { ROUNDS1 = 5 };
30
31enum { ROUNDS2 = 18 };
32
33typedef struct {
34    slice s;
35    size_t i;
36} Parser;
37
38static int space(uint8_t c) {
39    return c == ' ' || c == '\t' || c == '\r' || c == '\n';
40}
41
42static void ws(Parser *p) {
43    while (p->i < p->s.l && space(p->s.p[p->i])) {
44        p->i++;
45    }
46}
47
48static void text(Parser *p, const char *s) {
49    size_t n = strlen(s);
50    aoc_assert(n <= p->s.l - p->i && !memcmp(p->s.p + p->i, s, n), "bad input");
51    p->i += n;
52}
53
54static void finish(Parser *p) {
55    ws(p);
56    aoc_assert(p->i == p->s.l, "trailing input");
57}
58
59static slice line(Parser *p) {
60    size_t b = p->i;
61    while (p->i < p->s.l && p->s.p[p->i] != '\n') {
62        p->i++;
63    }
64    size_t e = p->i;
65    if (e > b && p->s.p[e - 1] == '\r') {
66        e--;
67    }
68    if (p->i < p->s.l) {
69        p->i++;
70    }
71    return (slice){b ? p->s.p + b : p->s.p, e - b};
72}
73
74static int rules2[PAT2], rules3[PAT3], transition[PAT3][GRID], ready[PAT3];
75
76static int pattern(Parser *p, int size) {
77    int bits = 0;
78    for (int y = 0; y < size; y++) {
79        if (y) {
80            text(p, "/");
81        }
82        for (int x = 0; x < size; x++) {
83            aoc_assert(p->i < p->s.l, "short pattern");
84            uint8_t c = p->s.p[p->i++];
85            aoc_assert(c == '.' || c == '#', "bad pixel");
86            bits |= (c == '#') << (y * size + x);
87        }
88    }
89    return bits;
90}
91
92static inline __attribute__((always_inline)) size_t
93measure_pattern_width(Parser q, size_t k) {
94    while (k < q.s.l && q.s.p[k] != '/') {
95        k++;
96    }
97
98    return k;
99}
100
101static inline __attribute__((always_inline)) void
102rotate_pattern_point(int s, int rot, int *xx_ref, int *yy_ref) {
103    for (int r = 0; r < rot; r++) {
104        int t = (*xx_ref);
105        (*xx_ref) = s - 1 - (*yy_ref);
106        (*yy_ref) = t;
107    }
108}
109
110static inline __attribute__((always_inline)) int
111transform_pattern_grid(int s, int a, int flip, int rot, int v) {
112    for (int y = 0; y < s; y++) {
113        for (int x = 0; x < s; x++) {
114            int xx = flip ? s - 1 - x : x, yy = y;
115            rotate_pattern_point(s, rot, &xx, &yy);
116            v |= ((a >> (y * s + x)) & 1) << (yy * s + xx);
117        }
118    }
119
120    return v;
121}
122
123static inline __attribute__((always_inline)) void
124add_rotated_rules(int s, int a, int b, int *rule, int flip) {
125    for (int rot = 0; rot < 4; rot++) {
126        int v = 0;
127        v = transform_pattern_grid(s, a, flip, rot, v);
128        aoc_assert(rule[v] < 0 || rule[v] == b, "conflicting rules");
129        rule[v] = b;
130    }
131}
132
133static inline __attribute__((always_inline)) void
134add_reflected_rules(int s, int a, int b, int *rule) {
135    for (int flip = 0; flip < 2; flip++) {
136        add_rotated_rules(s, a, b, rule, flip);
137    }
138}
139
140static int load(slice in) {
141    for (int i = 0; i < PAT2; i++) {
142        rules2[i] = -1;
143    }
144    for (int i = 0; i < PAT3; i++) {
145        rules3[i] = -1;
146    }
147    memset(ready, 0, sizeof ready);
148    Parser p = {in, 0};
149    int rows = 0;
150    while (p.i < in.l) {
151        Parser q = {line(&p), 0};
152        size_t k = 0;
153        k = measure_pattern_width(q, k);
154        aoc_assert(k == 2 || k == 3, "bad pattern size");
155        int s = (int)k, a = pattern(&q, s);
156        text(&q, " => ");
157        int b = pattern(&q, s + 1);
158        finish(&q);
159        int *rule = s == 2 ? rules2 : rules3;
160        add_reflected_rules(s, a, b, rule);
161        aoc_assert(++rows <= RULES, "too many rules");
162    }
163    aoc_assert(rows, "empty rules");
164    return rows;
165}
166
167static inline __attribute__((always_inline)) int
168read_fractal_block(uint8_t *a, int n, int block, int y, int x, int v) {
169    for (int j = 0; j < block; j++) {
170        for (int i = 0; i < block; i++) {
171            v |= a[(y + j) * n + x + i] << (j * block + i);
172        }
173    }
174
175    return v;
176}
177
178static inline __attribute__((always_inline)) void
179write_fractal_block(uint8_t *b, int block, int next, int y, int x, int out) {
180    for (int j = 0; j <= block; j++) {
181        for (int i = 0; i <= block; i++) {
182            b[(y / block * (block + 1) + j) * next + x / block * (block + 1) +
183              i] = (uint8_t)((out >> (j * (block + 1) + i)) & 1);
184        }
185    }
186}
187
188static int expand(uint8_t *a, int n, uint8_t *b) {
189    int block = n % 2 ? 3 : 2, next = n / block * (block + 1);
190    for (int y = 0; y < n; y += block) {
191        for (int x = 0; x < n; x += block) {
192            int v = 0;
193            v = read_fractal_block(a, n, block, y, x, v);
194            int out = block == 2 ? rules2[v] : rules3[v];
195            aoc_assert(out >= 0, "missing enhancement rule");
196            write_fractal_block(b, block, next, y, x, out);
197        }
198    }
199    return next;
200}
201
202static int expand_pattern(int bits, int rounds, uint8_t a[CELLS]) {
203    uint8_t b[CELLS];
204    for (int i = 0; i < GRID; i++) {
205        a[i] = (uint8_t)((bits >> i) & 1);
206    }
207    int n = 3;
208    for (int r = 0; r < rounds; r++) {
209        n = expand(a, n, b);
210        memcpy(a, b, (size_t)n * n);
211    }
212    return n;
213}
214
215static inline __attribute__((always_inline)) int
216read_transition_block(uint8_t a[CELLS], int y, int x, int v) {
217    for (int j = 0; j < 3; j++) {
218        for (int i = 0; i < 3; i++) {
219            v |= a[(3 * y + j) * GRID + 3 * x + i] << (3 * j + i);
220        }
221    }
222
223    return v;
224}
225
226static inline __attribute__((always_inline)) void
227cache_pattern_transition(int p, uint8_t a[CELLS]) {
228    for (int y = 0; y < 3; y++) {
229        for (int x = 0; x < 3; x++) {
230            int v = 0;
231            v = read_transition_block(a, y, x, v);
232            transition[p][3 * y + x] = v;
233        }
234    }
235}
236
237static inline __attribute__((always_inline)) void
238count_transition_outputs(int64_t counts[PAT3], int64_t next[PAT3], int p) {
239    for (int i = 0; i < GRID; i++) {
240        next[transition[p][i]] += counts[p];
241    }
242}
243
244static inline __attribute__((always_inline)) void
245expand_pattern_counts(int64_t counts[PAT3], int64_t next[PAT3]) {
246    for (int p = 0; p < PAT3; p++) {
247        if (counts[p]) {
248            if (!ready[p]) {
249                uint8_t a[CELLS];
250                expand_pattern(p, 3, a);
251                cache_pattern_transition(p, a);
252                ready[p] = 1;
253            }
254            count_transition_outputs(counts, next, p);
255        }
256    }
257}
258
259static inline __attribute__((always_inline)) int
260count_lit_pixels(uint8_t a[CELLS], int n, int sum) {
261    for (int i = 0; i < n * n; i++) {
262        sum += a[i];
263    }
264
265    return sum;
266}
267
268static slice solve(slice in, int rounds) {
269    load(in);
270    int64_t counts[PAT3] = {0}, next[PAT3];
271    counts[482] = 1; /* .#./..#/###, row-major bits */
272    while (rounds >= 3) {
273        memset(next, 0, sizeof next);
274        expand_pattern_counts(counts, next);
275        memcpy(counts, next, sizeof counts);
276        rounds -= 3;
277    }
278    int64_t answer = 0;
279    for (int p = 0; p < PAT3; p++) {
280        if (counts[p]) {
281            uint8_t a[CELLS];
282            int n = expand_pattern(p, rounds, a), sum = 0;
283            sum = count_lit_pixels(a, n, sum);
284            answer += counts[p] * sum;
285        }
286    }
287    return slice_from_i64(answer);
288}
289
290slice part1(slice in) {
291    return solve(in, ROUNDS1);
292}
293
294slice part2(slice in) {
295    return solve(in, ROUNDS2);
296}
297
298const struct aoc_method aoc_methods[] = {
299    {0, 0},
300};

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

An expanding picture is an invitation to worry about exponential growth. First put numbers on it. Starting at width three, the first five widths are 4, 6, 9, 12, and 18. Part one ends with only 324 pixels. Build the picture directly, split it into blocks, apply the rules, and join the results. There is plenty of room to understand the mechanics before seeking a shortcut.

The rule lookup hides two easy mistakes. When the size is divisible by both two and three, the two-by-two split wins; width six must therefore use two-by-two blocks. Also, rotations and reflections help match the input pattern, but the output stays exactly as written in the rulebook. Rotating the output back would invent a different enhancement process. The example's four differently oriented blocks all produce the same orientation of the replacement.

A two-by-two pattern has only sixteen possible bit arrangements, and a three-by-three has 512. The local book has six small rules and 102 large ones. Rather than rotate every block and search the book repeatedly, fill a lookup table with all rotations and reflections of each rule's input. Some variants coincide because a pattern is symmetric; that is fine unless two rules demand different outputs for the same variant. A few bits now identify a rule directly.

Part two asks for eighteen rounds. The width reaches 2,187, giving 4,782,969 pixels. That is a substantial jump from 324, but it is still a feasible direct simulation on a normal computer: all eighteen rounds together write about 8.8 million output pixels. We should not pretend the straightforward approach would take months. The more interesting question is whether counting lit pixels really requires preserving the entire picture.

At first, counting small patterns seems dangerous. Blocks can be split differently on the next round, so neighboring pieces might interact. Follow one aligned three-by-three tile for three rounds: it becomes four by four, then six by six, then nine by nine. The intermediate two-by-two cuts stay inside that tile's boundaries. At the end it can be partitioned into nine three-by-three tiles, ready for the same three-round process. The boundaries line up again.

That is the point where we can safely forget arrangement. Equal three-by-three tiles produce equal collections of nine descendants, wherever they occur. Keep a count for each of the 512 possible patterns. Expand each encountered pattern once through three rounds, cache its nine descendants, and multiply those contributions by how many copies we have. Eighteen rounds become six updates of this small histogram. The final image contains 531,441 three-by-three tiles, but counting them does not require storing them individually.

For five rounds, perform one three-round update and expand each remaining pattern for the final two rounds before adding its lit pixels. The implementation uses at most a nine-by-nine temporary image and 512 pattern counts, with up to 528 rule lines. It rejects conflicting rules and any missing rule actually needed by the expansion. The public two-rule example supports two rounds and twelve lit pixels; it is not a complete rulebook for the fixed five- or eighteen-round endpoints. The shortcut rests on aligned boundaries, not on a hopeful assumption that all local patterns evolve independently at every round.

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.