fix 12b
[advent21.git] / 13b.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
11 void add_dot(struct dot **grid, struct point p)
12 {
13 struct dot *d;
14 HASH_FIND(hh, *grid, &p, sizeof(struct point), d);
15 if (!d) {
16 d = malloc(sizeof(struct dot));
17 d->p = p;
18 HASH_ADD(hh, *grid, p, sizeof(struct point), d);
19 }
20 }
21
22 #define foldp(p, f) ( (f) - ( (p) - (f) ) )
23
24 void fold(struct dot **grid, char axis, int num)
25 {
26 struct dot *d, *tmp;
27 HASH_ITER(hh, *grid, d, tmp) {
28 struct point p = d->p;
29 if (axis == 'x' && p.x >= num) {
30 HASH_DEL(*grid, d);
31 if (p.x > num)
32 add_dot(grid, pnt(foldp(p.x, num), p.y));
33 } else if (axis == 'y' && p.y >= num) {
34 HASH_DEL(*grid, d);
35 if (p.y > num)
36 add_dot(grid, pnt(p.x, foldp(p.y, num)));
37 }
38 }
39 }
40
41 int main()
42 {
43 char *buf = NULL;
44 size_t len = 0;
45 struct dot *grid = NULL;
46
47 while (getline(&buf, &len, stdin) != -1 && strcmp(buf, "\n") != 0) {
48 char *to = strchr(buf, ',');
49 *(to++)= '\0';
50 add_dot(&grid, pnt(atoi(buf), atoi(to)));
51 }
52 while (getline(&buf, &len, stdin) != -1) {
53 char *to = strchr(buf, '=');
54 fold (&grid, *(to-1), atoi(to+1));
55 }
56
57 int maxx = 0, maxy = 0;
58 for (struct dot *d = grid; d!=NULL; d = d->hh.next) {
59 maxx = maxx < d->p.x ? d->p.x : maxx;
60 maxy = maxy < d->p.y ? d->p.y : maxy;
61 }
62
63 struct dot *d;
64 for (int y = 0; y<=maxy; y++) {
65 for (int x = 0; x<=maxx; x++) {
66 HASH_FIND(hh, grid, &pnt(x, y), sizeof(struct point), d);
67 printf("%c", d ? '#' : '.');
68 }
69 printf("\n");
70 }
71 }