day 1 golfed M4 500 significant bytes
[aoc_eblake.git] / 2017 / advent22.c
blob7067aa881485f2a50b5c09a98d84f5b2f24058dd
1 #define _GNU_SOURCE 1
2 #include <stdio.h>
3 #include <string.h>
4 #include <stdlib.h>
5 #include <unistd.h>
6 #include <stdbool.h>
7 #include <ctype.h>
8 #include <assert.h>
10 #define MAX 3000 // guessing that 10000 iterations won't grow that large
12 enum dir {
17 } d;
19 enum state {
26 static enum state grid[MAX][MAX];
28 int
29 main (int argc, char **argv)
31 int cycles = 10000000;
32 if (argc > 1)
33 cycles = atoi (argv[1]);
34 ssize_t nread;
35 size_t len = 0;
36 char *line = NULL;
37 bool first = true;
38 int x, y;
39 int count = 0;
40 while ((nread = getline(&line, &len, stdin)) >= 0) {
41 if (first) {
42 assert ((nread & 1) == 0);
43 first = false;
44 x = y = MAX / 2 - nread / 2;
45 printf ("populating starting at %d,%d\n", x, y);
47 char *p = line;
48 while (*p != '\n') {
49 if (*p++ == '#')
50 grid[y][x] = I;
51 x++;
53 y++;
54 x -= p - line;
55 count++;
57 x += count / 2;
58 y -= count / 2 + 1;
59 printf ("parsed %dx%d inputs, starting at %d,%d\n", count, count, x, y);
60 int infected = 0;
61 for (int i = 0; i < cycles; i++) {
62 switch (grid[y][x]) {
63 case C:
64 d += 3;
65 break;
66 case W:
67 break;
68 case I:
69 d++;
70 break;
71 case F:
72 d += 2;
73 break;
74 default:
75 assert (false);
77 infected += (grid[y][x] = (grid[y][x] + 1) % 4) == I;
78 switch (d % 4) {
79 case U:
80 y--;
81 break;
82 case R:
83 x++;
84 break;
85 case D:
86 y++;
87 break;
88 case L:
89 x--;
90 break;
91 default:
92 assert (false);
94 if (!x || !y || x == MAX - 1 || y == MAX - 1) {
95 printf ("grid is too small at iteration %d\n", i);
96 return 1;
99 printf ("after %d cycles, infected %d nodes\n", cycles, infected);
100 return 0;