day 18 golfed m4 squeeze a bit more
[aoc_eblake.git] / 2019 / day2.c
blobf3cd96b158cc1d7588d4af4e5c75ff0395962e09
1 #define _GNU_SOURCE 1
2 #include <stdio.h>
3 #include <string.h>
4 #include <stdlib.h>
5 #include <stdarg.h>
6 #include <stdbool.h>
8 #define LIMIT 400
9 static int a[LIMIT];
10 static int len;
12 static int do_debug = -1;
13 void debug(const char *fmt, ...) {
14 va_list ap;
15 if (do_debug < 0)
16 do_debug = !!getenv("DEBUG");
17 if (do_debug > 0) {
18 va_start(ap, fmt);
19 vfprintf(stderr, fmt, ap);
20 va_end(ap);
24 void dump(void) {
25 if (!do_debug)
26 return;
27 for (int i = 0; i < len; i++)
28 debug("%d,", a[i]);
29 debug("\n");
32 int main(int argc, char **argv) {
33 int i, *pc, count = 0;
34 bool done = false;
36 if (argc > 1)
37 if (!(stdin = freopen(argv[1], "r", stdin))) {
38 perror("failure");
39 exit(2);
42 while (scanf("%d%*[,\n]", &i) == 1) {
43 a[len++] = i;
44 if (len > LIMIT) {
45 printf("recompile with larger LIMIT\n");
46 exit(2);
49 printf("Read %u slots\n", len);
50 dump();
52 if (argc > 3) {
53 a[1] = atoi(argv[2]);
54 a[2] = atoi(argv[3]);
57 pc = a;
58 while (!done) {
59 count++;
60 if (pc[0] == 99) {
61 debug("halting\n");
62 } else {
63 debug("executing %d,%d(%d),%d(%d),%d\n", pc[0], pc[1], a[pc[1]],
64 pc[2], a[pc[2]], pc[3]);
65 if (pc - a >= len || pc[1] >= len || pc[2] >= len || pc[3] >= len) {
66 printf("out-of-bounds reference at instruction %d\n", (int)(pc - a));
67 exit(1);
70 switch (*pc) {
71 case 1:
72 a[pc[3]] = a[pc[1]] + a[pc[2]];
73 break;
74 case 2:
75 a[pc[3]] = a[pc[1]] * a[pc[2]];
76 break;
77 case 99:
78 done = true;
79 break;
81 pc += 4;
82 dump();
84 printf("after %d opcodes, slot 0 holds %d\n", count, a[0]);
85 dump();
86 return 0;