summary refs log tree commit diff homepage
path: root/2020
diff options
context:
space:
mode:
authorJune McEnroe <june@causal.agency>2020-12-11 00:27:05 -0500
committerJune McEnroe <june@causal.agency>2020-12-11 00:27:05 -0500
commitf3506ad1182206f38b4c261d409e9e029c68c052 (patch)
treef0b9cf204bc1071d73b0db11725f645d547f7103 /2020
parentSolve day 11 part 1 (diff)
downloadaoc-f3506ad1182206f38b4c261d409e9e029c68c052.tar.gz
aoc-f3506ad1182206f38b4c261d409e9e029c68c052.zip
Solve day 11 part 2
Diffstat (limited to '2020')
-rw-r--r--2020/day11.c54
1 files changed, 52 insertions, 2 deletions
diff --git a/2020/day11.c b/2020/day11.c
index f8552ca..360cf49 100644
--- a/2020/day11.c
+++ b/2020/day11.c
@@ -21,7 +21,7 @@ static int adj(const struct Grid *grid, int y, int x) {
 		(at(grid, y + 1, x + 1) == '#')
 	);
 }
-static struct Grid gen(const struct Grid *prev) {
+static struct Grid gen1(const struct Grid *prev) {
 	struct Grid next = { .h = prev->h, .w = prev->w };
 	for (int y = 0; y < next.h; ++y) {
 		for (int x = 0; x < next.w; ++x) {
@@ -36,6 +36,43 @@ static struct Grid gen(const struct Grid *prev) {
 	}
 	return next;
 }
+static char ray(const struct Grid *grid, int y, int x, int dy, int dx) {
+	y += dy;
+	x += dx;
+	while (y >= 0 && y < grid->h && x >= 0 && x < grid->w) {
+		if (grid->c[y][x] != '.') return grid->c[y][x];
+		y += dy;
+		x += dx;
+	}
+	return '.';
+}
+static int see(const struct Grid *grid, int y, int x) {
+	return (
+		(ray(grid, y, x, -1, -1) == '#') +
+		(ray(grid, y, x, -1, +0) == '#') +
+		(ray(grid, y, x, -1, +1) == '#') +
+		(ray(grid, y, x, +0, -1) == '#') +
+		(ray(grid, y, x, +0, +1) == '#') +
+		(ray(grid, y, x, +1, -1) == '#') +
+		(ray(grid, y, x, +1, +0) == '#') +
+		(ray(grid, y, x, +1, +1) == '#')
+	);
+}
+static struct Grid gen2(const struct Grid *prev) {
+	struct Grid next = { .h = prev->h, .w = prev->w };
+	for (int y = 0; y < next.h; ++y) {
+		for (int x = 0; x < next.w; ++x) {
+			if (prev->c[y][x] == 'L' && !see(prev, y, x)) {
+				next.c[y][x] = '#';
+			} else if (prev->c[y][x] == '#' && see(prev, y, x) >= 5) {
+				next.c[y][x] = 'L';
+			} else {
+				next.c[y][x] = prev->c[y][x];
+			}
+		}
+	}
+	return next;
+}
 int main(void) {
 	struct Grid init = {0};
 	while (EOF != scanf("%s\n", init.c[init.h])) {
@@ -44,7 +81,7 @@ int main(void) {
 	init.w = strlen(init.c[0]);
 	struct Grid prev = init;
 	for (;;) {
-		struct Grid next = gen(&prev);
+		struct Grid next = gen1(&prev);
 		if (!memcmp(&next, &prev, sizeof(next))) break;
 		prev = next;
 	}
@@ -55,4 +92,17 @@ int main(void) {
 		}
 	}
 	printf("%d\n", occ);
+	prev = init;
+	for (;;) {
+		struct Grid next = gen2(&prev);
+		if (!memcmp(&next, &prev, sizeof(next))) break;
+		prev = next;
+	}
+	occ = 0;
+	for (int y = 0; y < prev.h; ++y) {
+		for (int x = 0; x < prev.w; ++x) {
+			occ += prev.c[y][x] == '#';
+		}
+	}
+	printf("%d\n", occ);
 }