2015 / Day 21

RPG Simulator 20XX

Read the original puzzle on adventofcode.com ↗

The solution

C11

solution.c

1#include "aoc.h"
2
3#include <stdlib.h>
4#include <string.h>
5
6/* 2015 day 21. RPG Simulator. */
7
8static char *cstrstr(const char *hay, const char *needle) {
9    size_t nlen = strlen(needle);
10    size_t hlen = strlen(hay);
11    size_t i;
12    if (nlen == 0) {
13        return (char *)hay;
14    }
15    for (i = 0; i + nlen <= hlen; i++) {
16        if (memcmp(hay + i, needle, nlen) == 0) {
17            return (char *)hay + i;
18        }
19    }
20    return 0;
21}
22
23static int find_int_after(const char *text, const char *label, int *out) {
24    const char *p = cstrstr(text, label);
25    if (!p) {
26        return 0;
27    }
28    p += strlen(label);
29    while (*p &&
30           (*p == ' ' || *p == '\t' || *p == ':' || *p == '\r' || *p == '\n')) {
31        p++;
32    }
33    if (*p < '0' || *p > '9') {
34        return 0;
35    }
36    int v = 0;
37    while (*p >= '0' && *p <= '9') {
38        aoc_assert(v <= (1000000 - (*p - '0')) / 10, "bad boss stat");
39        v = v * 10 + (*p - '0');
40        p++;
41    }
42    *out = v;
43    return 1;
44}
45
46static void boss_stats(slice input, int *hp, int *dmg, int *arm) {
47    /* copy input to null-terminated buffer */
48    char buf[4096];
49    size_t n = input.l;
50    aoc_assert(n < sizeof buf, "boss input too long");
51    memcpy(buf, input.p, n);
52    buf[n] = 0;
53    aoc_assert(find_int_after(buf, "Hit Points", hp), "bad boss hp");
54    aoc_assert(find_int_after(buf, "Damage", dmg), "bad boss damage");
55    aoc_assert(find_int_after(buf, "Armor", arm), "bad boss armor");
56    aoc_assert(*hp > 0 && *dmg > 0, "bad boss stat");
57}
58
59/* equipment */
60typedef struct {
61    int cost, dmg, arm;
62} Item;
63
64static const Item weapons[] = {
65    {8, 4, 0}, {10, 5, 0}, {25, 6, 0}, {40, 7, 0}, {74, 8, 0}};
66static const int NWEP = 5;
67static const Item armors[] = {{0, 0, 0},  {13, 0, 1}, {31, 0, 2},
68                              {53, 0, 3}, {75, 0, 4}, {102, 0, 5}};
69static const int NARM = 6;
70/* six real rings */
71static const Item ringlist[] = {{25, 1, 0}, {50, 2, 0}, {100, 3, 0},
72                                {20, 0, 1}, {40, 0, 2}, {80, 0, 3}};
73static const int NRINGS = 6;
74
75static int win(int playerHP, int pdmg, int parm, int bossHP, int bossDmg,
76               int bossArm) {
77    int pHit = pdmg - bossArm;
78    if (pHit < 1) {
79        pHit = 1;
80    }
81    int bHit = bossDmg - parm;
82    if (bHit < 1) {
83        bHit = 1;
84    }
85    /* turns to kill */
86    int tBoss = (bossHP + pHit - 1) / pHit;
87    int tPlayer = (playerHP + bHit - 1) / bHit;
88    return tBoss <= tPlayer;
89}
90
91static void enumerate(int part, slice input, int64_t *out) {
92    int bh, bd, ba;
93    boss_stats(input, &bh, &bd, &ba);
94    int playerHP = 100;
95    int64_t bestWin = INT64_MAX;
96    int anyWin = 0;
97    int64_t bestLose = -1;
98    int w, a;
99    for (w = 0; w < NWEP; w++) {
100        for (a = 0; a < NARM; a++) {
101            /* masks of chosen rings 0..63 */
102            int mask;
103            for (mask = 0; mask < (1 << NRINGS); mask++) {
104                /* count bits */
105                int bits = 0;
106                int mm = mask;
107                while (mm) {
108                    bits += mm & 1;
109                    mm >>= 1;
110                }
111                if (bits > 2) {
112                    continue;
113                }
114                int cost = weapons[w].cost + armors[a].cost;
115                int dmg = weapons[w].dmg + armors[a].dmg;
116                int arm = weapons[w].arm + armors[a].arm;
117                int rr;
118                for (rr = 0; rr < NRINGS; rr++) {
119                    if (mask & (1 << rr)) {
120                        cost += ringlist[rr].cost;
121                        dmg += ringlist[rr].dmg;
122                        arm += ringlist[rr].arm;
123                    }
124                }
125                int wflag = win(playerHP, dmg, arm, bh, bd, ba);
126                if (wflag) {
127                    if (cost < bestWin) {
128                        bestWin = cost;
129                        anyWin = 1;
130                    }
131                } else {
132                    if (cost > bestLose) {
133                        bestLose = cost;
134                    }
135                }
136            }
137        }
138    }
139    if (part == 1) {
140        aoc_assert(anyWin, "no winning config");
141        *out = bestWin;
142    } else {
143        aoc_assert(bestLose >= 0, "no losing config");
144        *out = bestLose;
145    }
146}
147
148slice part1(slice input) {
149    int64_t out = 0;
150    enumerate(1, input, &out);
151    return slice_from_i64(out);
152}
153
154slice part2(slice input) {
155    int64_t out = 0;
156    enumerate(2, input, &out);
157    return slice_from_i64(out);
158}
159
160/* The bounded search: every loadout the solver will try. Parsing the
161 * boss first refuses a malformed body before the enumeration runs.
162 */
163static slice estimate(slice input) {
164    int hp, dmg, arm;
165    int64_t ring_sets;
166    boss_stats(input, &hp, &dmg, &arm);
167    ring_sets =
168        1 + (int64_t)NRINGS + ((int64_t)NRINGS * ((int64_t)NRINGS - 1)) / 2;
169    return slice_from_i64((int64_t)NWEP * (int64_t)NARM * ring_sets);
170}
171
172const struct aoc_method aoc_methods[] = {
173    {"estimate", estimate},
174    {0, 0},
175};

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

Henry hands us the controller, and a shop full of gear invites some serious build planning. How many outfits are there, though? Choose one of five weapons, one of five armor pieces or none, and zero, one, or two distinct rings from six. The ring choices number 1 + 6 + 15 = 22. That makes only 5 × 6 × 22 = 660 outfits. We can afford to try on the entire shop.

Be careful with the shop rules before counting. Armor is optional; a weapon is compulsory. Two rings are an unordered pair, and buying two copies of the same ring is forbidden. Treating the hands as separate choices would introduce duplicates and could accidentally allow equipment the shop does not sell.

Simulating each fight would be fine. The local boss has 100 hit points and single-digit damage and armor, and every attack removes at least one hit point. But halfway through tracing the example, a thought interrupts the battle: haven't we already seen every kind of turn? The damage never changes. Only the hit-point counters move. We can count the hits needed instead of acting them out.

If our effective damage is d, it takes ceiling(boss hit points / d) attacks to win. Compute the boss's required attacks in the same way, using our 100 hit points. Effective damage is always at least one, even against stronger armor. The player attacks first, so equal attack counts mean we win: our final blow lands before the boss gets its corresponding turn. In the story's small example both sides need four hits, which explains the narrow victory.

Evaluate the 660 outfits and keep the cheapest winner. Then the shopkeeper reveals his allegiance: part 2 wants the most expensive way to lose. What a miserable shopping trip. Happily, the calculation survives his betrayal unchanged; keep the largest cost among losing outfits. More money does not guarantee more useful combat strength, since damage and armor help in different ways. Trying every outfit saves us from having to trust either the prices or the shopkeeper.

The estimate method returns the exact 660-outfit search size. The implementation uses the fixed shop and a 100-hit-point player, accepts boss statistics through 1,000,000 with positive hit points and damage, and limits the boss description to fewer than 4,096 characters. It explicitly rejects a part when no outfit has the requested win or loss outcome. The main simplification comes from noticing that a deterministic fight with constant damage has no decisions left to simulate.

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.