day 12 part two wrong, day 13 done
[advent21.git] / 13a.c
diff --git a/13a.c b/13a.c
new file mode 100644 (file)
index 0000000..bd315ce
--- /dev/null
+++ b/13a.c
@@ -0,0 +1,61 @@
+#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;
+       bool dots = true;
+
+       while (getline(&buf, &len, stdin) != -1) {
+               if (strcmp(buf, "\n") == 0) {
+                       dots = false;
+               } else if (dots) {
+                       char *to = strchr(buf, ',');
+                       *(to++)= '\0';
+                       add_dot(&grid, pnt(atoi(buf), atoi(to)));
+               } else {
+                       char *to = strchr(buf, '=');
+                       fold (&grid, *(to-1), atoi(to+1));
+                       break;
+               }
+       }
+       printf("%d\n", HASH_COUNT(grid));
+}