day 22 part 1
[aoc_eblake.git] / 2018 / day4b.c
blobb7ed00b3c0c91ff3ae6aaa55008c3102d3433bae
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 #define LIMIT 3500
19 short array[LIMIT][60];
20 char list[LIMIT];
22 static void process(int guard, int start, int end) {
23 debug("processing %d: %d-%d\n", guard, start, end);
24 for (int i = start; i < end; i++)
25 array[guard][i]++;
28 int main(int argc, char **argv) {
29 size_t len = 0, count = 0;
30 char *line;
31 int i, j;
32 int guard;
33 int sleep, wake;
34 char *p;
35 bool pair = false;
37 if (argc > 1)
38 if (!(stdin = freopen(argv[1], "r", stdin))) {
39 perror("failure");
40 exit(2);
43 while (getline(&line, &len, stdin) >= 0) {
44 count++;
45 if (pair) {
46 p = strchr(line, ':');
47 if (!p) {
48 fprintf(stderr, "bad input\n");
49 exit(1);
51 wake = (p[1] - '0') * 10 + p[2] - '0';
52 process(guard, sleep, wake);
53 pair = false;
54 } else {
55 p = strchr(line, '#');
56 if (p) {
57 if (sscanf(p, "#%d ", &guard) != 1) {
58 fprintf(stderr, "bad input\n");
59 exit(1);
61 if (guard >= LIMIT) {
62 printf("recompile with larger LIMIT!\n");
63 exit(1);
65 list[guard]++;
66 } else {
67 p = strchr(line, ':');
68 if (!p) {
69 fprintf(stderr, "bad input\n");
70 exit(1);
72 sleep = (p[1] - '0') * 10 + p[2] - '0';
73 pair = true;
77 printf("read %zd lines\n", count);
78 int best_guard = 0;
79 int total_sleep = 0;
80 int best_minute = 0;
81 for (i = 0; i < LIMIT; i++) {
82 int local_minute = 0;
83 int local_sleep = 0;
84 if (!list[i])
85 continue;
86 for (j = 0; j < 60; j++) {
87 local_sleep += array[i][j];
88 if (array[i][j] > array[i][local_minute])
89 local_minute = j;
91 debug("guard %d slept %d best minute %d: %d\n", i, local_sleep,
92 local_minute, array[i][local_minute]);
93 if (array[i][local_minute] > total_sleep) {
94 total_sleep = array[i][local_minute];
95 best_guard = i;
96 best_minute = local_minute;
99 printf("best guard %d at minute %d = %d\n", best_guard, best_minute,
100 best_guard * best_minute);
101 return 0;