cleanup
[advent21.git] / 13a.c
1 #include <stdio.h>
2 #include <stdbool.h>
3
4 #include <uthash.h>
5
6 struct point { int x; int y; };
7 struct dot { struct point p; UT_hash_handle hh; };
8
9 #define pnt(px, py) ((struct point){.x=(px), .y=(py)})
10 void add_dot(struct dot **grid, struct point p)
11 {
12 struct dot *d;
13 HASH_FIND(hh, *grid, &p, sizeof(struct point), d);
14 if (!d) {
15 d = malloc(sizeof(struct dot));
16 d->p = p;
17 HASH_ADD(hh, *grid, p, sizeof(struct point), d);
18 }
19 }
20
21 #define foldp(p, f) ( (f) - ( (p) - (f) ) )
22
23 void fold(struct dot **grid, char axis, int num)
24 {
25 struct dot *d, *tmp;
26 HASH_ITER(hh, *grid, d, tmp) {
27 struct point p = d->p;
28 if (axis == 'x' && p.x >= num) {
29 HASH_DEL(*grid, d);
30 if (p.x > num)
31 add_dot(grid, pnt(foldp(p.x, num), p.y));
32 } else if (axis == 'y' && p.y >= num) {
33 HASH_DEL(*grid, d);
34 if (p.y > num)
35 add_dot(grid, pnt(p.x, foldp(p.y, num)));
36 }
37 }
38 }
39
40 int main()
41 {
42 char *buf = NULL;
43 size_t len = 0;
44 struct dot *grid = NULL;
45 bool dots = true;
46
47 while (getline(&buf, &len, stdin) != -1) {
48 if (strcmp(buf, "\n") == 0) {
49 dots = false;
50 } else if (dots) {
51 char *to = strchr(buf, ',');
52 *(to++)= '\0';
53 add_dot(&grid, pnt(atoi(buf), atoi(to)));
54 } else {
55 char *to = strchr(buf, '=');
56 fold (&grid, *(to-1), atoi(to+1));
57 break;
58 }
59 }
60 printf("%d\n", HASH_COUNT(grid));
61 }