day 12 part two wrong, day 13 done
[advent21.git] / 13b.c
diff --git a/13b.c b/13b.c
new file mode 100644 (file)
index 0000000..092cf7a
--- /dev/null
+++ b/13b.c
@@ -0,0 +1,71 @@
+#include <stdio.h>
+#include <stdbool.h>
+
+#include <uthash.h>
+
+struct point { int x; int y; };
+struct dot { struct point p; UT_hash_handle hh; };
+
+#define pnt(px, py) ((struct point){.x=(px), .y=(py)})
+
+void add_dot(struct dot **grid, struct point p)
+{
+       struct dot *d;
+       HASH_FIND(hh, *grid, &p, sizeof(struct point), d);
+       if (!d) {
+               d = malloc(sizeof(struct dot));
+               d->p = p;
+               HASH_ADD(hh, *grid, p, sizeof(struct point), d);
+       }
+}
+
+#define foldp(p, f) ( (f) - ( (p) - (f) ) )
+
+void fold(struct dot **grid, char axis, int num)
+{
+       struct dot *d, *tmp;
+       HASH_ITER(hh, *grid, d, tmp) {
+               struct point p = d->p;
+               if (axis == 'x' && p.x >= num) {
+                       HASH_DEL(*grid, d);
+                       if (p.x > num)
+                               add_dot(grid, pnt(foldp(p.x, num), p.y));
+               } else if (axis == 'y' && p.y >= num) {
+                       HASH_DEL(*grid, d);
+                       if (p.y > num)
+                               add_dot(grid, pnt(p.x, foldp(p.y, num)));
+               }
+       }
+}
+
+int main()
+{
+       char *buf = NULL;
+       size_t len = 0;
+       struct dot *grid = NULL;
+
+       while (getline(&buf, &len, stdin) != -1 && strcmp(buf, "\n") != 0) {
+               char *to = strchr(buf, ',');
+               *(to++)= '\0';
+               add_dot(&grid, pnt(atoi(buf), atoi(to)));
+       }
+       while (getline(&buf, &len, stdin) != -1) {
+               char *to = strchr(buf, '=');
+               fold (&grid, *(to-1), atoi(to+1));
+       }
+
+       int maxx = 0, maxy = 0;
+       for (struct dot *d = grid; d!=NULL; d = d->hh.next) {
+               maxx = maxx < d->p.x ? d->p.x : maxx;
+               maxy = maxy < d->p.y ? d->p.y : maxy;
+       }
+
+       struct dot *d;
+       for (int y = 0; y<=maxy; y++) {
+               for (int x = 0; x<=maxx; x++) {
+                       HASH_FIND(hh, grid, &pnt(x, y), sizeof(struct point), d);
+                       printf("%c", d ? '#' : '.');
+               }
+               printf("\n");
+       }
+}