2015 / Day 06
Probably a Fire Hazard
Read the original puzzle on adventofcode.com ↗
The solution
solution.c
1#include "aoc.h"
2
3#include <stdlib.h>
4#include <string.h>
5
6/* 2015 day 6. Grid of lights 1000x1000. */
7
8enum { N = 1000 };
9
10enum { MAXCMD = 10000 };
11
12static int is_space(uint8_t c) {
13 return c == ' ' || c == '\t' || c == '\r' || c == '\n';
14}
15
16static int g_mode[MAXCMD];
17static int g_x1[MAXCMD];
18static int g_y1[MAXCMD];
19static int g_x2[MAXCMD];
20static int g_y2[MAXCMD];
21static int g_ncmd = 0;
22
23static int parse_uint(slice in, size_t *i, int *out, int maxv) {
24 int v = 0;
25 int nd = 0;
26 if (*i >= in.l || in.p[*i] < '0' || in.p[*i] > '9') {
27 return 0;
28 }
29 while (*i < in.l && in.p[*i] >= '0' && in.p[*i] <= '9') {
30 v = v * 10 + (int)(in.p[*i] - '0');
31 if (v > maxv) {
32 return 0;
33 }
34 (*i)++;
35 nd++;
36 if (nd > 5) {
37 return 0;
38 }
39 }
40 *out = v;
41 return 1;
42}
43
44static void skip_spaces(slice in, size_t *i) {
45 while (*i < in.l && (in.p[*i] == ' ' || in.p[*i] == '\t')) {
46 (*i)++;
47 }
48}
49
50static void expect_word(slice in, size_t *i, const char *w) {
51 size_t j = 0;
52 while (w[j]) {
53 aoc_assert(*i < in.l && in.p[*i] == (uint8_t)w[j], "bad command");
54 (*i)++;
55 j++;
56 }
57}
58
59/* Parses all commands into globals without allocating grid. */
60static inline __attribute__((always_inline)) size_t
61skip_blank_lines(slice input, size_t i) {
62 while (i < input.l && (input.p[i] == '\r' || input.p[i] == '\n')) {
63 i++;
64 }
65
66 return i;
67}
68
69static void load(slice input) {
70 size_t i = 0;
71 int n = 0;
72 while (1) {
73 int mode = 0;
74 int x1, y1, x2, y2, t;
75 skip_spaces(input, &i);
76 i = skip_blank_lines(input, i);
77 skip_spaces(input, &i);
78 if (i >= input.l) {
79 break;
80 }
81 aoc_assert(n < MAXCMD, "too many commands");
82 if (i + 5 <= input.l && memcmp(input.p + i, "turn ", 5) == 0) {
83 i += 5;
84 if (i + 3 <= input.l && memcmp(input.p + i, "on ", 3) == 0) {
85 mode = 1;
86 i += 3;
87 } else {
88 aoc_assert(i + 4 <= input.l &&
89 memcmp(input.p + i, "off ", 4) == 0,
90 "bad command");
91 mode = 0;
92 i += 4;
93 }
94 } else {
95 aoc_assert(i + 7 <= input.l &&
96 memcmp(input.p + i, "toggle ", 7) == 0,
97 "bad command");
98 mode = 2;
99 i += 7;
100 }
101 aoc_assert(parse_uint(input, &i, &x1, N - 1), "bad coordinate");
102 aoc_assert(i < input.l && input.p[i] == ',', "bad coordinate");
103 i++;
104 aoc_assert(parse_uint(input, &i, &y1, N - 1), "bad coordinate");
105 skip_spaces(input, &i);
106 expect_word(input, &i, "through");
107 skip_spaces(input, &i);
108 aoc_assert(parse_uint(input, &i, &x2, N - 1), "bad coordinate");
109 aoc_assert(i < input.l && input.p[i] == ',', "bad coordinate");
110 i++;
111 aoc_assert(parse_uint(input, &i, &y2, N - 1), "bad coordinate");
112
113 if (x1 > x2) {
114 t = x1;
115 x1 = x2;
116 x2 = t;
117 }
118 if (y1 > y2) {
119 t = y1;
120 y1 = y2;
121 y2 = t;
122 }
123
124 g_mode[n] = mode;
125 g_x1[n] = x1;
126 g_y1[n] = y1;
127 g_x2[n] = x2;
128 g_y2[n] = y2;
129 n++;
130 }
131 aoc_assert(n > 0, "empty input");
132 g_ncmd = n;
133}
134
135/* The mode branch lives per row, not per cell, and the loops are tight
136 * pointer walks: every executed basic block in the cell loop carries a
137 * store, which is what keeps the real 18M-cell input inside the wasm
138 * execution budget.
139 */
140static inline __attribute__((always_inline)) void
141switch_rectangle(uint8_t grid[N * N], int *c_ref) {
142 int mode = g_mode[(*c_ref)];
143 size_t x1 = (size_t)g_x1[(*c_ref)], y1 = (size_t)g_y1[(*c_ref)];
144 size_t x2 = (size_t)g_x2[(*c_ref)], y2 = (size_t)g_y2[(*c_ref)];
145 size_t w = x2 - x1 + 1;
146 uint8_t *row = grid + y1 * (size_t)N + x1;
147 size_t y;
148 for (y = y1; y <= y2; y++) {
149 uint8_t *p = row;
150 uint8_t *e = row + w;
151 if (mode == 1) {
152 while (p < e) {
153 *p = 1;
154 p++;
155 }
156 } else if (mode == 0) {
157 while (p < e) {
158 *p = 0;
159 p++;
160 }
161 } else {
162 while (p < e) {
163 *p ^= 1;
164 p++;
165 }
166 }
167 row += (size_t)N;
168 }
169}
170
171slice part1(slice input) {
172 static uint8_t grid[N * N];
173 int64_t lit = 0;
174 int c;
175 load(input);
176 memset(grid, 0, sizeof grid);
177 for (c = 0; c < g_ncmd; c++) {
178 switch_rectangle(grid, &c);
179 }
180 uint8_t *p = grid;
181 uint8_t *e = grid + (size_t)N * (size_t)N;
182 while (p < e) {
183 lit += *p;
184 p++;
185 }
186 return slice_from_i64(lit);
187}
188
189static inline __attribute__((always_inline)) void
190brighten_rectangle(int32_t grid[N * N], int *c_ref) {
191 int mode = g_mode[(*c_ref)];
192 size_t x1 = (size_t)g_x1[(*c_ref)], y1 = (size_t)g_y1[(*c_ref)];
193 size_t x2 = (size_t)g_x2[(*c_ref)], y2 = (size_t)g_y2[(*c_ref)];
194 size_t w = x2 - x1 + 1;
195 int32_t *row = grid + y1 * (size_t)N + x1;
196 size_t y;
197 for (y = y1; y <= y2; y++) {
198 int32_t *p = row;
199 int32_t *e = row + w;
200 if (mode == 1) {
201 while (p < e) {
202 *p = *p + 1;
203 p++;
204 }
205 } else if (mode == 0) {
206 /* branchless floor at zero: no per-cell branch */
207 while (p < e) {
208 int v = *p;
209 *p = v > 0 ? v - 1 : 0;
210 p++;
211 }
212 } else {
213 while (p < e) {
214 *p = *p + 2;
215 p++;
216 }
217 }
218 row += (size_t)N;
219 }
220}
221
222slice part2(slice input) {
223 static int32_t grid[N * N];
224 int64_t total = 0;
225 int c;
226 load(input);
227 memset(grid, 0, sizeof grid);
228 for (c = 0; c < g_ncmd; c++) {
229 brighten_rectangle(grid, &c);
230 }
231 int32_t *p = grid;
232 int32_t *e = grid + (size_t)N * (size_t)N;
233 while (p < e) {
234 total += *p;
235 p++;
236 }
237 return slice_from_i64(total);
238}
239
240const struct aoc_method aoc_methods[] = {
241 {0, 0},
242};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
One million lights. It is easy to see that number and start designing a clever rectangle data structure before touching the input. Let's count the actual work first. The local instructions contain 300 rectangles whose inclusive areas add up to 18,246,724 light updates. We do not visit the whole million-light grid for every command, only the affected rectangle. Eighteen million simple updates are a much friendlier proposition than the story's extravagant display first suggests.
A grid and two nested loops are therefore a reasonable first attempt. For part 1, each cell is on or off. Process the commands in order, then count the lit cells. One small detail deserves a hand check: 0,0 through 2,2 includes both endpoints, so it is a three-by-three square of nine lights. Getting that wrong would make a beautifully fast implementation consistently wrong around every edge.
Once overlapping rectangles are working, the direct simulation is rather comforting. We do not have to reason separately about each overlap: every affected light simply receives its next instruction. Then part 2 reveals the translation mistake. These lights have brightness controls. Our on/off model has done its job for the first star, but it cannot represent what the new commands mean.
Keep the rectangle traversal and give each cell a nonnegative brightness. On adds one, toggle adds two, and off subtracts one with a floor at zero. At first this looks like an opportunity to add all rectangle contributions together and apply them once. That would be a lovely shortcut. Try off then on at a dark light, though: it ends at one. Reverse those same commands and it ends at zero. The clamp has made order matter, so a plain rectangle-addition difference table throws away something essential.
Fortunately, we already estimated a manageable direct approach. There is no obligation to rescue the clever idea after that counterexample. The straightforward grid keeps the needed history and lets us get on with the puzzle. This is a useful kind of solver confidence: knowing when the plain loop deserves to survive part 2.
The implementation uses a fixed 1,000-by-1,000 grid and accepts at most 10,000 commands with coordinates 0–999. Brightness can gain at most two per command, so each cell stays at or below 20,000; the total uses 64 bits. Large accepted command lists may still exhaust the shared work budget. The measured 18.2 million updates explain the choice for this input, rather than promising that every list of 10,000 rectangles will be cheap.
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.