cleanup
[advent21.git] / 13b.c
1 #include <stdio.h>
2
3 #include <uthash.h>
4
5 struct point { int x; int y; };
6 struct dot { struct point p; UT_hash_handle hh; };
7
8 #define pnt(px, py) ((struct point){.x=(px), .y=(py)})
9
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
46 while (getline(&buf, &len, stdin) != -1 && strcmp(buf, "\n") != 0) {
47 char *to = strchr(buf, ',');
48 *(to++)= '\0';
49 add_dot(&grid, pnt(atoi(buf), atoi(to)));
50 }
51
52 int maxx = 0, maxy = 0;
53 while (getline(&buf, &len, stdin) != -1) {
54 char *to = strchr(buf, '=')-1;
55 int foldline = atoi(to+2);
56 fold (&grid, *to, foldline--);
57 if (*to == 'x') maxx = foldline;
58 else maxy = foldline;
59 }
60
61 struct dot *d;
62 for (int y = 0; y<=maxy; y++) {
63 for (int x = 0; x<=maxx; x++) {
64 HASH_FIND(hh, grid, &pnt(x, y), sizeof(struct point), d);
65 printf("%c", d ? '#' : '.');
66 }
67 printf("\n");
68 }
69 }