2017 / Day 14
Disk Defragmentation
Read the original puzzle on adventofcode.com ↗
The solution
solution.c
1#include "aoc.h"
2
3/* 2017 day 14. Each row is one knot hash of "key-N", and the used
4 * squares are those bits, most-significant first. Part 1 counts
5 * them. Part 2 flood-fills each four-connected region on that same
6 * grid and clears it, so a region is never copied out and no second
7 * map is built.
8 *
9 * The disk is the story's fixed square. A legitimate key is one
10 * nonempty line of printable ASCII, short enough that "key-127"
11 * fits the length buffer. "bad key", "key exceeds cap", or "bad
12 * disk key" otherwise.
13 *
14 * Bounds: SIDE = 128 and CELLS = SIDE * SIDE, so the flood queue
15 * holds every cell and the walk is one pass. The key is at most
16 * KEYMAX bytes; the knot lengths stay inside LENGTHS.
17 *
18 * The real key is 8 alphanumeric bytes. Each of the 128 rows hashes that key,
19 * a hyphen, and the row number. KEYMAX = 64 is the refusal above those 8
20 * bytes.
21 */
22
23enum { SIDE = 128, CELLS = SIDE * SIDE };
24
25enum { KEYCAP = 1024, SUFFIX = 5, LENGTHS = KEYCAP + SUFFIX };
26
27enum { KEYMAX = 64, KEYBUF = 68 };
28
29static inline __attribute__((always_inline)) void
30reverse_knot_segment(uint8_t *a, int *pos, int len) {
31 for (int j = 0; j < len / 2; j++) {
32 int x = (*pos + j) & 255, y = (*pos + len - 1 - j) & 255;
33 uint8_t t = a[x];
34 a[x] = a[y];
35 a[y] = t;
36 }
37}
38
39static void round_(uint8_t a[256], const uint8_t *lengths, size_t n, int *pos,
40 int *skip) {
41 for (size_t i = 0; i < n; i++) {
42 int len = lengths[i];
43 reverse_knot_segment(a, pos, len);
44 *pos = (*pos + len + *skip) & 255;
45 *skip = (*skip + 1) & 255;
46 }
47}
48
49static inline __attribute__((always_inline)) uint8_t
50xor_dense_block(uint8_t a[256], int i, uint8_t v) {
51 for (int j = 0; j < 16; j++) {
52 v ^= a[16 * i + j];
53 }
54
55 return v;
56}
57
58static void knot(const uint8_t *s, size_t n, uint8_t digest[16]) {
59 aoc_assert(n <= KEYCAP, "key exceeds cap");
60 uint8_t lengths[LENGTHS], a[256];
61 if (n) {
62 memcpy(lengths, s, n);
63 }
64 const uint8_t suffix[SUFFIX] = {17, 31, 73, 47, 23};
65 memcpy(lengths + n, suffix, SUFFIX);
66 for (int i = 0; i < 256; i++) {
67 a[i] = (uint8_t)i;
68 }
69 int pos = 0, skip = 0;
70 for (int r = 0; r < 64; r++) {
71 round_(a, lengths, n + SUFFIX, &pos, &skip);
72 }
73 for (int i = 0; i < 16; i++) {
74 uint8_t v = 0;
75 v = xor_dense_block(a, i, v);
76 digest[i] = v;
77 }
78}
79
80static slice key(slice in) {
81 if (in.l && in.p[in.l - 1] == '\n') {
82 in.l--;
83 }
84 if (in.l && in.p[in.l - 1] == '\r') {
85 in.l--;
86 }
87 aoc_assert(in.l <= KEYCAP, "key exceeds cap");
88 for (size_t i = 0; i < in.l; i++) {
89 aoc_assert(in.p[i] >= 32 && in.p[i] <= 126, "bad key");
90 }
91 return in;
92}
93
94static uint8_t grid[SIDE][SIDE];
95static int queue_[CELLS];
96
97static void load(slice in) {
98 in = key(in);
99 aoc_assert(in.l && in.l <= KEYMAX, "bad disk key");
100 uint8_t s[KEYBUF], digest[16];
101 memcpy(s, in.p, in.l);
102 s[in.l] = '-';
103 for (int y = 0; y < SIDE; y++) {
104 char *end = aoc_printf("%d", (char *)s + in.l + 1, y);
105 knot(s, (size_t)(end - (char *)s), digest);
106 for (int x = 0; x < SIDE; x++) {
107 grid[y][x] = (digest[x / 8] >> (7 - x % 8)) & 1;
108 }
109 }
110}
111
112slice part1(slice in) {
113 load(in);
114 int n = 0;
115 for (int y = 0; y < SIDE; y++) {
116 for (int x = 0; x < SIDE; x++) {
117 n += grid[y][x];
118 }
119 }
120 return slice_from_i64(n);
121}
122
123static inline __attribute__((always_inline)) int
124enqueue_region_neighbors(int t, int xx, int yy, const int dx[4],
125 const int dy[4]) {
126 for (int d = 0; d < 4; d++) {
127 int a = xx + dx[d], b = yy + dy[d];
128 if (a >= 0 && a < SIDE && b >= 0 && b < SIDE && grid[b][a]) {
129 grid[b][a] = 0;
130 queue_[t++] = b * SIDE + a;
131 }
132 }
133
134 return t;
135}
136
137static inline __attribute__((always_inline)) void flood_region(int *h_ref,
138 int *t_ref) {
139 while ((*h_ref) < (*t_ref)) {
140 int v = queue_[(*h_ref)++], xx = v % SIDE, yy = v / SIDE;
141 const int dx[4] = {-1, 1, 0, 0}, dy[4] = {0, 0, -1, 1};
142 (*t_ref) = enqueue_region_neighbors((*t_ref), xx, yy, dx, dy);
143 }
144}
145
146slice part2(slice in) {
147 load(in);
148 int count = 0;
149 for (int y = 0; y < SIDE; y++) {
150 for (int x = 0; x < SIDE; x++) {
151 if (grid[y][x]) {
152 count++;
153 int h = 0, t = 1;
154 queue_[0] = y * SIDE + x;
155 grid[y][x] = 0;
156 flood_region(&h, &t);
157 }
158 }
159 }
160 return slice_from_i64(count);
161}
162
163const struct aoc_method aoc_methods[] = {
164 {0, 0},
165};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
A disk defragmenter sounds like it ought to move files. Read the questions before building one: today we only count occupied squares, then connected regions. The entire disk is 128 by 128, just 16,384 cells. A plain grid is already small enough. The unusual work is discovering what is in it.
The knot hash from day ten is back. Each row hashes the key, a hyphen, and that row's decimal number, starting at zero. This is a good moment to reuse a working idea rather than reopen its mysteries. Start each row with a fresh ring and run the full 64-round hash. The local key has eight characters, so the row strings have ten through twelve characters before the five-value suffix. Across the disk that means 128 hashes and 132,224 reversals, containing about five million swaps: substantial compared with counting cells, but a perfectly ordinary finite job.
The hash's hexadecimal spelling is only a representation. Its sixteen dense values already contain the 128 bits we need. Read each value from its highest bit to its lowest, giving one row of the grid. Leading zeroes are real free squares; dropping them would shift everything that follows. Part one can simply count set bits. Storing the whole grid is also cheap and leaves us ready for whatever the second star asks.
Then part two reveals why arrangement matters. Knowing that a row has fifty used squares says nothing about whether they join the row above. Worse, the little picture in the story shows separated pieces of region eight that reconnect outside the displayed corner. We cannot decide regions from the cropped example or count horizontal runs as if each were isolated.
This is the village from day twelve wearing a different costume. A used square is a program, and each used neighbor above, below, left, or right is a pipe. Diagonal touches do not count; opposite edges do not wrap. Find an unvisited used square, count a new region, and flood outward through those four connections. Mark each square as soon as it enters the work list, so two neighbors cannot enqueue it twice. When the flood stops, the next remaining used square belongs to a different region.
We can erase squares as we visit them because their original values will never be needed again. Every used square enters the queue once, with at most four neighboring positions checked. Even a completely full disk would need only 65,536 neighbor checks. The supposedly harder second part adds little beside the hashing. There is no reason to invent a cleverer region algorithm for this size.
The implementation accepts a nonempty printable ASCII key of at most 64 characters, covering the observed eight-character key. The grid and queue are fixed by the story: 128 rows, 128 columns, and at most 16,384 queued cells. The public key's 8,108 used squares and 1,242 regions check two different things: bit generation and connectivity. A matching population alone would not expose reversed bit order or accidental diagonal connections.
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.