summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAdam Spragg <adam@spra.gg>2022-12-28 14:58:43 +0000
committerAdam Spragg <adam@spra.gg>2022-12-28 14:58:43 +0000
commit985d8d2db0cb743f5fd1982b5c5af4615eb53931 (patch)
tree699df718dd7a898d2b04042f6addb31a48d81206
parentfaffa0a4855d94224ddcd119f0b33f8bca5254b4 (diff)
Solve puzzle 23 part 2
-rw-r--r--23.c62
1 files changed, 47 insertions, 15 deletions
diff --git a/23.c b/23.c
index 24d2c3d..99a3fb7 100644
--- a/23.c
+++ b/23.c
@@ -3,6 +3,7 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
+#include <unistd.h>
#define arrlen(x) (sizeof(x)/sizeof((x)[0]))
@@ -249,14 +250,36 @@ grid_dump(char * buf, int cols, int rows)
int
-main()
+main(int argc, char ** argv)
{
+ int rounds = 10;
char * buf = NULL, * pch;
int bufsiz = 0, buflen = 0;
int cols, rows, round;
int xmin, xmax, ymin, ymax, i, j;
int empty;
+ while ((i = getopt(argc, argv, "p:r:")) != -1) {
+ switch (i) {
+ case 'p':
+ switch (atoi(optarg)) {
+ case 1: rounds = 10; break;
+ case 2: rounds = -1; break;
+ default:
+ fprintf(stderr, "Unexpected part %s\n", optarg);
+ return -1;
+ }
+ break;
+
+ case 'r':
+ rounds = atoi(optarg);
+ break;
+
+ default:
+ return -1;
+ }
+ }
+
// Read input
while (1) {
size_t n;
@@ -294,9 +317,9 @@ main()
}
// Do rounds of movement simulation
- for (round = 0; round < 10; ++round) {
+ for (round = 0; round < rounds || rounds < 0; ++round) {
char * psrc, * pdest;
- int dir;
+ int dir, moves = 0;
// Get current bounding box.
if (bounding(&xmin, &xmax, &ymin, &ymax, buf, cols, rows) != 0) {
@@ -428,6 +451,7 @@ main()
pdest = posd(buf, cols, rows, i, j, dir);
*pdest = '#';
*psrc = '.';
+ ++moves;
}
else if (loc_proposed(*psrc)) {
// Clean up count of elves who wanted to move here.
@@ -436,28 +460,36 @@ main()
}
}
+ if (!moves)
+ break;
+
#if 0
fprintf(stderr, "Round %d\n", round + 1);
grid_dump(buf, cols, rows);
#endif
}
- // Find the number of empty cells in the bounding box
- empty = 0;
- if (bounding(&xmin, &xmax, &ymin, &ymax, buf, cols, rows) != 0) {
- fprintf(stderr, "Can't find bounding box!\n");
- free(buf);
- return -1;
+ if (rounds < 0) {
+ printf("Number of rounds needed to stabilise: %d\n", round + 1);
}
- for (j = ymin; j < ymax; ++j) {
- for (i = xmin; i < xmax; ++i) {
- if (loc_clear(*pos(buf, cols, rows, i, j))) {
- ++empty;
+ else {
+ // Find the number of empty cells in the bounding box
+ empty = 0;
+ if (bounding(&xmin, &xmax, &ymin, &ymax, buf, cols, rows) != 0) {
+ fprintf(stderr, "Can't find bounding box!\n");
+ free(buf);
+ return -1;
+ }
+ for (j = ymin; j < ymax; ++j) {
+ for (i = xmin; i < xmax; ++i) {
+ if (loc_clear(*pos(buf, cols, rows, i, j))) {
+ ++empty;
+ }
}
}
- }
- printf("Number of empty spaces: %d\n", empty);
+ printf("Number of empty spaces after %d rounds: %d\n", rounds, empty);
+ }
// Tidy and exit
free(buf);