2016 / Day 21
Scrambled Letters and Hash
Read the original puzzle on adventofcode.com ↗
The solution
solution.c
1#include "aoc.h"
2
3#include <string.h>
4
5/* 2016 day 21. Scramble operations. The passwords are story text,
6 * not puzzle input, so they are hardcoded: part 1 scrambles
7 * "abcdefgh", part 2 un-scrambles "fbgdceah" by walking the list
8 * backwards with inverse operations.
9 *
10 * Every operation inverts except "rotate based on position of
11 * letter": the forward step rotates right by 1 + index + (index >= 4)
12 * and the index moves with the rotation, so the inverse tries each of
13 * the 8 rotations and keeps the one whose forward step reproduces the
14 * string (the index-to-shift map is a permutation on 8 letters, so
15 * exactly one lands). Rotations reduce mod 8 first — the story's own
16 * example rotates right 6 on a 5-letter string.
17 *
18 * Bounds: at most OPMAX = 1024 operations (the real list has 100),
19 * positions 0..7 inside the 8-letter password, numbers up to 4
20 * digits, refused beyond with "bad operation",
21 * "position out of range", "too many operations", or
22 * "letter not in password". The operation list is static.
23 */
24
25enum { PWLEN = 8 };
26
27enum { OPMAX = 1024 };
28
29enum { NUMDIGITS = 4 };
30
31enum { OP_SWAPPOS, OP_SWAPLET, OP_ROT, OP_ROTBAS, OP_REV, OP_MOVE };
32
33enum { DIR_LEFT = 0, DIR_RIGHT = 1 };
34
35struct op {
36 uint8_t kind;
37 uint8_t dir;
38 uint8_t x; /* letter operand (swap letter / rotate based) */
39 uint8_t y;
40 int16_t a;
41 int16_t b;
42};
43
44static struct op ops[OPMAX];
45static int nops;
46
47#define AT(s, i, end, lit) at((s), (i), (end), (lit), sizeof(lit) - 1)
48
49static int at(const uint8_t *s, size_t *i, size_t end, const char *lit,
50 size_t n) {
51 if (*i + n <= end && memcmp(s + *i, lit, n) == 0) {
52 *i += n;
53 return 1;
54 }
55 return 0;
56}
57
58static int num(const uint8_t *s, size_t *i, size_t end, int *out) {
59 int v = 0;
60 int nd = 0;
61
62 while (*i < end && s[*i] >= '0' && s[*i] <= '9') {
63 nd++;
64 aoc_assert(nd <= NUMDIGITS, "bad operation");
65 v = v * 10 + (s[*i] - '0');
66 (*i)++;
67 }
68 aoc_assert(nd > 0, "bad operation");
69 *out = v;
70 return v;
71}
72
73static int16_t num16(const uint8_t *s, size_t *i, size_t end) {
74 int v = 0;
75
76 num(s, i, end, &v);
77 return (int16_t)v;
78}
79
80static uint8_t letter(const uint8_t *s, size_t *i, size_t end) {
81 uint8_t c;
82
83 aoc_assert(*i < end && s[*i] >= 'a' && s[*i] <= 'z', "bad operation");
84 c = s[*i];
85 (*i)++;
86 aoc_assert(*i == end || s[*i] == ' ', "bad operation");
87 return c;
88}
89
90static inline __attribute__((always_inline)) size_t
91find_instruction_end(slice input, size_t eol) {
92 while (eol < input.l && input.p[eol] != '\n') {
93 eol++;
94 }
95
96 return eol;
97}
98
99static void load(slice input) {
100 size_t i = 0;
101
102 nops = 0;
103 aoc_assert(input.l <= 65536, "input too long");
104 while (i < input.l) {
105 size_t eol = i;
106 struct op o;
107
108 eol = find_instruction_end(input, eol);
109 if (eol > i && input.p[eol - 1] == '\r') {
110 eol--;
111 }
112 if (eol == i) {
113 i++;
114 continue;
115 }
116 memset(&o, 0, sizeof o);
117 if (AT(input.p, &i, eol, "swap position ")) {
118 o.kind = OP_SWAPPOS;
119 o.a = num16(input.p, &i, eol);
120 aoc_assert(AT(input.p, &i, eol, " with position "),
121 "bad operation");
122 o.b = num16(input.p, &i, eol);
123 aoc_assert(o.a <= PWLEN - 1 && o.b <= PWLEN - 1,
124 "position out of range");
125 } else if (AT(input.p, &i, eol, "swap letter ")) {
126 o.kind = OP_SWAPLET;
127 o.x = letter(input.p, &i, eol);
128 aoc_assert(AT(input.p, &i, eol, " with letter "), "bad operation");
129 o.y = letter(input.p, &i, eol);
130 } else if (AT(input.p, &i, eol, "rotate ")) {
131 if (AT(input.p, &i, eol, "left ")) {
132 o.kind = OP_ROT;
133 o.dir = DIR_LEFT;
134 o.a = num16(input.p, &i, eol);
135 } else if (AT(input.p, &i, eol, "right ")) {
136 o.kind = OP_ROT;
137 o.dir = DIR_RIGHT;
138 o.a = num16(input.p, &i, eol);
139 } else {
140 aoc_assert(AT(input.p, &i, eol, "based on position of letter "),
141 "bad operation");
142 o.kind = OP_ROTBAS;
143 o.x = letter(input.p, &i, eol);
144 }
145 if (o.kind == OP_ROT) {
146 aoc_assert(AT(input.p, &i, eol, " step"), "bad operation");
147 if (i < eol && input.p[i] == 's') {
148 i++;
149 }
150 }
151 } else if (AT(input.p, &i, eol, "reverse positions ")) {
152 o.kind = OP_REV;
153 o.a = num16(input.p, &i, eol);
154 aoc_assert(AT(input.p, &i, eol, " through "), "bad operation");
155 o.b = num16(input.p, &i, eol);
156 aoc_assert(o.a <= o.b, "bad operation");
157 aoc_assert(o.a <= PWLEN - 1 && o.b <= PWLEN - 1,
158 "position out of range");
159 } else if (AT(input.p, &i, eol, "move position ")) {
160 o.kind = OP_MOVE;
161 o.a = num16(input.p, &i, eol);
162 aoc_assert(AT(input.p, &i, eol, " to position "), "bad operation");
163 o.b = num16(input.p, &i, eol);
164 aoc_assert(o.a <= PWLEN - 1 && o.b <= PWLEN - 1,
165 "position out of range");
166 } else {
167 aoc_assert(0, "bad operation");
168 }
169 aoc_assert(i == eol, "bad operation");
170 aoc_assert(nops < OPMAX, "too many operations");
171 ops[nops++] = o;
172 i = eol;
173 if (i < input.l) {
174 i++;
175 }
176 }
177 aoc_assert(nops > 0, "no operations");
178}
179
180static int findc(const char *s, uint8_t c) {
181 int k;
182
183 for (k = 0; k < PWLEN; k++) {
184 if ((uint8_t)s[k] == c) {
185 return k;
186 }
187 }
188 aoc_assert(0, "letter not in password");
189 return -1;
190}
191
192/* Rotate s right by n (n already reduced mod PWLEN). */
193static void rot_right(char *s, int n) {
194 char t[PWLEN];
195 int k;
196
197 if (n == 0) {
198 return;
199 }
200 for (k = 0; k < PWLEN; k++) {
201 t[(k + n) % PWLEN] = s[k];
202 }
203 memcpy(s, t, PWLEN);
204}
205
206static void apply_one(const struct op *o, char *s) {
207 switch (o->kind) {
208 case OP_SWAPPOS: {
209 char t = s[o->a];
210 s[o->a] = s[o->b];
211 s[o->b] = t;
212 break;
213 }
214 case OP_SWAPLET: {
215 int p = findc(s, o->x);
216 int q = findc(s, o->y);
217 char t = s[p];
218 s[p] = s[q];
219 s[q] = t;
220 break;
221 }
222 case OP_ROT:
223 if (o->dir == DIR_RIGHT) {
224 rot_right(s, o->a % PWLEN);
225 } else {
226 rot_right(s, PWLEN - o->a % PWLEN);
227 }
228 break;
229 case OP_ROTBAS: {
230 int idx = findc(s, o->x);
231 int n = 1 + idx + (idx >= 4 ? 1 : 0);
232 rot_right(s, n % PWLEN);
233 break;
234 }
235 case OP_REV: {
236 int x = o->a;
237 int y = o->b;
238 while (x < y) {
239 char t = s[x];
240 s[x] = s[y];
241 s[y] = t;
242 x++;
243 y--;
244 }
245 break;
246 }
247 case OP_MOVE: {
248 char t = s[o->a];
249 if (o->a < o->b) {
250 memmove(s + o->a, s + o->a + 1, (size_t)(o->b - o->a));
251 } else if (o->a > o->b) {
252 memmove(s + o->b + 1, s + o->b, (size_t)(o->a - o->b));
253 }
254 s[o->b] = t;
255 break;
256 }
257 default:
258 aoc_assert(0, "bad operation");
259 }
260}
261
262/* The inverse of one operation. */
263static inline __attribute__((always_inline)) void
264rotate_password_candidate(char *s, char cand[PWLEN], int *r_ref, int *k_ref) {
265 for ((*k_ref) = 0; (*k_ref) < PWLEN; (*k_ref)++) {
266 cand[(*k_ref)] = s[((*k_ref) + (*r_ref)) % PWLEN];
267 }
268}
269
270static void undo_one(const struct op *o, char *s) {
271 if (o->kind == OP_ROT) {
272 if (o->dir == DIR_RIGHT) {
273 rot_right(s, PWLEN - o->a % PWLEN);
274 } else {
275 rot_right(s, o->a % PWLEN);
276 }
277 return;
278 }
279 if (o->kind == OP_MOVE) {
280 struct op back = *o;
281 back.a = o->b;
282 back.b = o->a;
283 apply_one(&back, s);
284 return;
285 }
286 if (o->kind == OP_ROTBAS) {
287 char cand[PWLEN];
288 char t[PWLEN];
289 int r;
290 int done = 0;
291
292 for (r = 0; r < PWLEN && !done; r++) {
293 int k;
294 rotate_password_candidate(s, cand, &r, &k);
295 memcpy(t, cand, PWLEN);
296 apply_one(o, t);
297 if (memcmp(t, s, PWLEN) == 0) {
298 memcpy(s, cand, PWLEN);
299 done = 1;
300 }
301 }
302 aoc_assert(done, "rotate inverse not found");
303 return;
304 }
305 apply_one(o, s); /* swap and reverse are their own inverse */
306}
307
308slice part1(slice input) {
309 char s[PWLEN] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'};
310 int k;
311
312 load(input);
313 for (k = 0; k < nops; k++) {
314 apply_one(&ops[k], s);
315 }
316 return slice_from_text(s, PWLEN);
317}
318
319slice part2(slice input) {
320 char s[PWLEN] = {'f', 'b', 'g', 'd', 'c', 'e', 'a', 'h'};
321 int k;
322
323 load(input);
324 for (k = nops - 1; k >= 0; k--) {
325 undo_one(&ops[k], s);
326 }
327 return slice_from_text(s, PWLEN);
328}
329
330const struct aoc_method aoc_methods[] = {
331 {0, 0},
332};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
Part 1 gives us a small machine to implement: apply each operation to an eight-letter string. The local input has 100 operations, so even copying the whole password for each one is negligible work. Follow the public example one operation at a time. It distinguishes swapping positions from swapping named letters, makes reversal endpoints inclusive, and shows that moving a letter means removing it before inserting it at its final index.
We finish the scrambler, then discover we cannot change the password file. Now we have to run the idea backward. Before groaning about inverse functions, count the possible inputs: every operation preserves the same eight distinct letters, so there are only 8! = 40,320 permutations. About four million operation applications would test them all with the scrambler we already trust. That is a perfectly credible escape route. The search is over rearrangements, not all eight-letter words.
We can also undo the process directly. Reverse the instruction order, then invert each operation. Swapping two positions or letters undoes itself. Reversing the same inclusive segment undoes itself. A fixed right rotation becomes a left rotation. Moving X to Y is undone by moving Y to X. The instruction order must reverse too: undoing an early operation while later operations are still in place acts on the wrong intermediate password.
Reversing feels easy until the position-based rotation. Rotate left by the amount suggested by the letter's current index? Try it, and it does not reliably return us to the start. The shift used the old index, which the shift itself changed. We could derive the inverse, but there are only eight possible predecessor rotations. Try each, run the forward rule, and keep the one that recreates the current string. A tiny brute-force search rescues the one awkward step.
There is still a question before trusting “the one”: could two predecessors work? Write out where indices 0 through 7 land: 1, 3, 5, 7, 2, 4, 6, 0. Every destination appears once. Good—eight letters give a unique predecessor. The five-letter example is more treacherous: indices 2 and 4 both land at zero. If our inverse behaves ambiguously on that example, it may be exposing a real property of the rule rather than a bug. Password length matters to the proof.
The implementation chooses reverse execution, using the forward-rule check for each of the local input's 17 position-based rotations. A useful final check is to scramble the recovered password again and verify that it returns the requested target. This combines the two approaches: reverse reasoning produces a candidate, and the simpler forward procedure verifies it.
The story fixes the starting password abcdefgh and target fbgdceah; the input supplies only operations. The implementation accepts 1–1,024 operations, positions 0–7, and numeric operands of at most four digits, reducing rotation amounts modulo eight. Letters used by an operation must occur in the password. Input text is limited to 65,536 characters. These bounds cover the measured 100-operation program.
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.