2018 / Day 15
Beverage Bandits
Read the original puzzle on adventofcode.com ↗
The solution
solution.c
1#include "aoc.h"
2
3typedef struct {
4 slice s;
5 size_t i;
6} Parser;
7
8static slice line(Parser *p) {
9 size_t b = p->i;
10 while (p->i < p->s.l && p->s.p[p->i] != '\n') {
11 p->i++;
12 }
13 size_t e = p->i;
14 if (e > b && p->s.p[e - 1] == '\r') {
15 e--;
16 }
17 if (p->i < p->s.l) {
18 p->i++;
19 }
20 return (slice){b ? p->s.p + b : p->s.p, e - b};
21}
22
23typedef struct {
24 int pos, hp, elf;
25} Unit;
26
27/* Combat is played, not searched. Turn order is fixed when the round
28 * starts. A destination tie takes reading order, the first step comes
29 * from a breadth-first search whose neighbors are already in that
30 * order, and an attack picks the lowest hit points, then reading order.
31 * The round stops before the next living unit would move, so a partial
32 * round is not scored. Elf powers run from 4 through POWER and a trial
33 * stops at the first elf death. Above POWER every hit already kills —
34 * units start at 200 hit points — so there is no higher power to try.
35 *
36 * The map is assumed to be one rectangle of at most SIDE by SIDE,
37 * holding both armies and at most UNITS units, and the fight is assumed
38 * to finish inside ROUNDS rounds and WORK expansions. A ragged row, a
39 * bad cell, an empty map, or a missing army is refused ("map exceeds
40 * cap", "ragged map", "bad map cell", "too many units", "empty battle",
41 * "both armies required"). A stall or a longer fight is "combat
42 * stalemate", "combat rounds exceed cap", "combat search exceeds cap",
43 * or "no lossless elf victory". SIDE is 64, so each search is one small
44 * grid and the power sweep stays inside WORK.
45 *
46 * The real cave is 32 by 32, with 10 elves and 20 goblins. A round is a turn
47 * of those 30 units. SIDE = 64 and UNITS = 128 are the refusals above that
48 * cave.
49 */
50enum { SIDE = 64, CELLS = SIDE * SIDE };
51
52enum { UNITS = 128 };
53
54enum { ROUNDS = 1000 };
55
56enum { POWER = 200 };
57
58enum { WORK = 20000000 };
59
60static Unit original[UNITS], units[UNITS];
61static uint8_t map[CELLS];
62static int16_t occupied[CELLS];
63static int dist[CELLS], first[CELLS], queue_[CELLS];
64static int w, h, n, totalwork;
65
66static void load(slice in) {
67 Parser p = {in, 0};
68 w = h = n = 0;
69 while (p.i < in.l) {
70 slice s = line(&p);
71 aoc_assert(h < SIDE && s.l > 0 && s.l <= SIDE, "map exceeds cap");
72 if (!h) {
73 w = (int)s.l;
74 }
75 aoc_assert(s.l == (size_t)w, "ragged map");
76 for (int x = 0; x < w; x++) {
77 uint8_t c = s.p[x];
78 aoc_assert(c == '#' || c == '.' || c == 'E' || c == 'G',
79 "bad map cell");
80 int pos = h * w + x;
81 if (c == 'E' || c == 'G') {
82 aoc_assert(n < UNITS, "too many units");
83 original[n++] = (Unit){pos, 200, c == 'E'};
84 c = '.';
85 }
86 map[pos] = c;
87 }
88 h++;
89 }
90 aoc_assert(n && w && h, "empty battle");
91}
92
93static void neighbors(int p, int out[4]) {
94 int x = p % w, y = p / w;
95 out[0] = y ? p - w : -1;
96 out[1] = x ? p - 1 : -1;
97 out[2] = x + 1 < w ? p + 1 : -1;
98 out[3] = y + 1 < h ? p + w : -1;
99}
100
101static int enemy(int id) {
102 int adj[4], best = -1;
103 neighbors(units[id].pos, adj);
104 for (int k = 0; k < 4; k++) {
105 if (adj[k] >= 0 && occupied[adj[k]]) {
106 int j = occupied[adj[k]] - 1;
107 if (units[j].elf != units[id].elf &&
108 (best < 0 || units[j].hp < units[best].hp ||
109 (units[j].hp == units[best].hp &&
110 units[j].pos < units[best].pos))) {
111 best = j;
112 }
113 }
114 }
115 return best;
116}
117
118static void move(int id) {
119 int start = units[id].pos;
120 for (int i = 0; i < w * h; i++) {
121 dist[i] = -1;
122 }
123 int head = 0, tail = 1;
124 queue_[0] = start;
125 dist[start] = 0;
126 first[start] = start;
127 while (head < tail) {
128 aoc_assert(++totalwork <= WORK, "combat search exceeds cap");
129 int p = queue_[head++], adj[4];
130 neighbors(p, adj);
131 for (int k = 0; k < 4; k++) {
132 int q = adj[k];
133 if (q < 0 || map[q] == '#' || occupied[q] || dist[q] >= 0) {
134 continue;
135 }
136 dist[q] = dist[p] + 1;
137 first[q] = p == start ? q : first[p];
138 queue_[tail++] = q;
139 }
140 }
141 int target = -1;
142 for (int j = 0; j < n; j++) {
143 if (units[j].hp > 0 && units[j].elf != units[id].elf) {
144 int adj[4];
145 neighbors(units[j].pos, adj);
146 for (int k = 0; k < 4; k++) {
147 int q = adj[k];
148 if (q >= 0 && dist[q] > 0 &&
149 (target < 0 || dist[q] < dist[target] ||
150 (dist[q] == dist[target] && q < target))) {
151 target = q;
152 }
153 }
154 }
155 }
156 if (target >= 0) {
157 occupied[start] = 0;
158 units[id].pos = first[target];
159 occupied[units[id].pos] = (int16_t)(id + 1);
160 }
161}
162
163static int64_t battle(int power, int no_death) {
164 memcpy(units, original, (size_t)n * sizeof units[0]);
165 memset(occupied, 0, sizeof occupied);
166 int elves = 0, goblins = 0;
167 for (int i = 0; i < n; i++) {
168 occupied[units[i].pos] = (int16_t)(i + 1);
169 elves += units[i].elf;
170 goblins += !units[i].elf;
171 }
172 aoc_assert(elves && goblins, "both armies required");
173 for (int round = 0; round < ROUNDS; round++) {
174 int order[UNITS], count = 0, progress = 0;
175 for (int i = 0; i < n; i++) {
176 if (units[i].hp > 0) {
177 int j = count++;
178 while (j && units[order[j - 1]].pos > units[i].pos) {
179 order[j] = order[j - 1];
180 j--;
181 }
182 order[j] = i;
183 }
184 }
185 for (int k = 0; k < count; k++) {
186 int id = order[k];
187 if (units[id].hp <= 0) {
188 continue;
189 }
190 if (!elves || !goblins) {
191 int64_t hp = 0;
192 for (int i = 0; i < n; i++) {
193 if (units[i].hp > 0) {
194 hp += units[i].hp;
195 }
196 }
197 return round * hp;
198 }
199 int target = enemy(id);
200 if (target < 0) {
201 int before = units[id].pos;
202 move(id);
203 progress |= before != units[id].pos;
204 target = enemy(id);
205 }
206 if (target >= 0) {
207 progress = 1;
208 units[target].hp -= units[id].elf ? power : 3;
209 if (units[target].hp <= 0) {
210 occupied[units[target].pos] = 0;
211 if (units[target].elf) {
212 elves--;
213 if (no_death) {
214 return -1;
215 }
216 } else {
217 goblins--;
218 }
219 }
220 }
221 }
222 aoc_assert(progress, "combat stalemate");
223 }
224 aoc_assert(0, "combat rounds exceed cap");
225 return -1;
226}
227
228slice part1(slice in) {
229 load(in);
230 totalwork = 0;
231 return slice_from_i64(battle(3, 0));
232}
233
234slice part2(slice in) {
235 load(in);
236 totalwork = 0;
237 for (int power = 4; power <= POWER; power++) {
238 int64_t result = battle(power, 1);
239 if (result >= 0) {
240 return slice_from_i64(result);
241 }
242 }
243 aoc_assert(0, "no lossless elf victory");
244}
245
246const struct aoc_method aoc_methods[] = {
247 {0, 0},
248};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
This is the day where a working battle can still be the wrong battle. The rules describe several different ties, all resolved in reading order but at different stages. The local cave is only 32 by 32, with 369 walkable cells, ten Elves, and twenty Goblins. The scale suggests ordinary simulation. The difficulty is turning the prose into the right sequence of decisions before optimizing anything.
There is no combat strategy for us to invent. Units follow a fixed policy, using the current board without predicting later turns. On a unit's turn, first check whether enemies remain. If an enemy is already adjacent, skip movement. Otherwise the destinations are open cells adjacent to enemies—not the enemies' occupied cells themselves. We are looking for the nearest reachable destination under unit-cost horizontal and vertical moves, which is exactly the setting for breadth-first search.
Why BFS? Its queue visits cells in layers of increasing distance, so the first reachable layer containing a destination gives the shortest distance. Walls and all other living units block movement. With at most 369 walkable cells here, even a full search is small. Thirty full searches would visit at most 11,070 cells in a round; actual combat often needs fewer because adjacent units attack without searching. The map gives us a solid reason to choose this familiar method.
Now separate two decisions that are easy to conflate. First choose the destination by shortest distance, then reading order. Only after that choose the first step on a shortest path to that particular destination, again in reading order. A path to a later destination does not win merely because its first step looks earlier. One clear implementation runs a second BFS backward from the selected destination. This implementation instead propagates each reached cell's first step during the forward BFS, visiting neighbors up, left, right, down so equal-length paths retain the earliest first step. It still compares destinations explicitly.
After movement, select an adjacent enemy by lowest hit points, then reading order. That is a different priority from movement. Damage and deaths take effect immediately: a dead unit's cell opens for later turns, and its scheduled turn is skipped. Fix the round's unit order before any unit moves, as with the carts, so crossing into an earlier cell does not grant an extra turn.
The final score has another trap. Combat ends when a living unit begins its turn and finds no enemies. If that happens midway through the round, the round is incomplete and contributes nothing. If the last enemy dies after every surviving unit has already taken its turn, the round can finish before combat is detected at the next round's start. Counting deaths or incrementing the round counter whenever the last enemy falls does not capture that distinction. The story's fully worked fight is valuable because we can compare intermediate positions and hit points, not just one final product.
Part two asks for the lowest Elf attack power that wins without any Elf dying. Reuse the exact simulation from a fresh initial board for each power, starting at four. Stop a failed trial immediately at the first Elf death; no later victory can repair that failure. This is a safe way to discard work because it follows directly from the success condition.
Trying powers in order also avoids relying on an unproved monotonicity assumption for binary search. Changing damage changes when cells become empty, which can change later movement and targeting. The range is finite for a stronger reason: at power 200 every Elf hit already kills any Goblin, since units start with 200 hit points and never heal. Larger powers cannot change that behavior. So there are at most 197 candidate powers to try.
The implementation supports rectangular maps up to 64 by 64 with at most 128 units and both armies present. Each fight is limited to 1,000 rounds, and the entire request has a shared budget of twenty million BFS expansions, including all power trials. It explicitly rejects stalemates or exhausted bounds. The breakthrough is matching each rule to a small, well-defined operation, then using the no-death condition to stop unsuccessful experiments early.
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.