day 22 part 1
[aoc_eblake.git] / 2018 / day7a.c
blob8281804a2f8e26c09f82e7b7cc26f61be3aeab8e
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 void debug(const char *fmt, ...) {
9 va_list ap;
10 if (getenv("DEBUG")) {
11 va_start(ap, fmt);
12 vfprintf(stderr, fmt, ap);
13 va_end(ap);
17 static struct data {
18 char state;
19 char wait[26];
20 } list[26];
22 int main(int argc, char **argv) {
23 size_t len = 0, count = 0;
24 char *line;
25 int i, j;
26 char a, b;
27 char *p;
29 /* Part 1 - read in lines */
30 if (argc > 1)
31 if (!(stdin = freopen(argv[1], "r", stdin))) {
32 perror("failure");
33 exit(2);
36 while (getline(&line, &len, stdin) >= 0) {
37 ++count;
38 if (sscanf(line, "Step %c must be finished before step %c can begin. ", &a,
39 &b) != 2 || (unsigned)(a-'A') > 25 || (unsigned)(b-'A') > 25) {
40 fprintf(stderr, "bad input\n");
41 exit(1);
43 list[a - 'A'].state = 1;
44 list[b - 'A'].state = 1;
45 strchrnul(list[b - 'A'].wait, '\0')[0] = a;
47 printf("Read %zu lines\n", count);
49 /* Part 2 - determine output */
50 for (i = 0; i < 26; i++)
51 for (j = 0; j < 26; j++) {
52 if (list[j].state != 1)
53 continue;
54 p = list[j].wait;
55 while (*p) {
56 if (list[*p - 'A'].state < 2)
57 break;
58 p++;
60 if (*p)
61 continue;
62 list[j].state = 2;
63 printf("%c", j + 'A');
64 break;
66 printf("\n");
67 return 0;