day 5
[advent21.git] / 05a.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <stdbool.h>
4
5 struct line { int x1; int y1; int x2; int y2; };
6
7 #define max(x, y) ((x)>(y) ? (x) : (y))
8 #define min(x, y) ((x)<(y) ? (x) : (y))
9 #define between(a, a1, a2) ((a) >= min(a1, a2) && (a) <= max(a1, a2))
10
11 int parse_lines(struct line lines[], int *maxx, int *maxy)
12 {
13 int i = 0;
14 char buf[1000];
15 while (fgets(buf, 1000, stdin) != NULL) {
16 char *p = &buf[0];
17 lines[i].x1 = strtol(p, &p, 10);
18 p++;
19 lines[i].y1 = strtol(p, &p, 10);
20 p+=4;
21 lines[i].x2 = strtol(p, &p, 10);
22 p++;
23 lines[i].y2 = strtol(p, &p, 10);
24 *maxx = max(*maxx, lines[i].x1);
25 *maxx = max(*maxx, lines[i].x2);
26 *maxy = max(*maxy, lines[i].y1);
27 *maxy = max(*maxy, lines[i].y2);
28 i++;
29 }
30 return i;
31 }
32
33 bool online(int x, int y, struct line line)
34 {
35 //Vertical
36 if (line.x1 == line.x2 && x == line.x1)
37 return between(y, line.y1, line.y2);
38 //Horizontal
39 if (line.y1 == line.y2 && y == line.y2)
40 return between(x, line.x1, line.x2);
41 return false;
42 }
43
44 int main()
45 {
46 struct line lines[1000];
47 int maxx = 0, maxy = 0;
48 int nlines = parse_lines(lines, &maxx, &maxy);
49 int r = 0;
50 for (int x = 0; x<=maxx; x++) {
51 for (int y = 0; y<=maxy; y++) {
52 int matches = 0;
53 for (int line = 0; line<nlines && matches < 2; line++)
54 if (online(x, y, lines[line]))
55 matches++;
56 r = matches >= 2 ? r+1 : r;
57 }
58 }
59 printf("%d\n", r);
60 }