2022 day 18 fix POSIX
[aoc_eblake.git] / 2019 / day8.c
blob878e1d2b8850a59f9b45755e07767f5698c211a3
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 static int debug_level = -1;
9 static void
10 debug_raw(int level, const char *fmt, ...) {
11 va_list ap;
12 if (debug_level < 0)
13 debug_level = atoi(getenv("DEBUG") ?: "0");
14 if (debug_level >= level) {
15 va_start(ap, fmt);
16 vfprintf(stderr, fmt, ap);
17 va_end(ap);
20 #define debug(...) debug_raw(1, __VA_ARGS__)
22 #define MAXX 25
23 #define MAXY 6
24 static char grid[MAXY][MAXX];
25 static int x = MAXX;
26 static int y = MAXY;
28 static void
29 dump(int level) {
30 int i, j;
31 if (debug_level < level)
32 return;
33 putchar('\n');
34 for (j = 0; j < y; j++) {
35 for (i = 0; i < x; i++)
36 putchar(" X-"[grid[j][i] - '0']);
37 putchar('\n');
41 int
42 main(int argc, char **argv) {
43 int zero = 0, one = 0, two = 0, min, best, count = 0, page, ch;
44 bool done = false;
46 debug("");
47 memset(grid, '2', sizeof grid);
48 if (argc > 2) {
49 x = atoi(argv[1]);
50 y = atoi(argv[2]);
52 else if (argc > 1)
53 if (!(stdin = freopen(argv[1], "r", stdin))) {
54 perror("failure");
55 exit(2);
58 min = page = x * y;
60 while (!done) {
61 ch = getchar();
62 switch (ch) {
63 case '0':
64 zero++;
65 break;
66 case '1':
67 one++;
68 break;
69 case '2':
70 two++;
71 break;
72 default:
73 done = true;
74 break;
76 if (grid[(count/x)%y][count%x] == '2')
77 grid[(count/x)%y][count%x] = ch;
78 if (!(count++ % page)) {
79 if (zero < min) {
80 min = zero;
81 best = one * two;
83 zero = one = two = 0;
84 dump(1);
87 printf("read %d bytes, best page value %d\n", count, best);
88 dump(0);
90 return 0;