summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAdam Spragg <adam@spra.gg>2022-12-08 18:34:30 +0000
committerAdam Spragg <adam@spra.gg>2022-12-08 18:34:30 +0000
commit631fe6892464c8b41cbff5ee1785ade2c24986c6 (patch)
tree8a98338aec054a2a3d4b1d7ae33a8956c0c7afb6
parent72588dff80018be3b5cdd9b5b54032913c57dfa2 (diff)
Solve puzzle 8 part 2
-rw-r--r--8.c73
1 files changed, 71 insertions, 2 deletions
diff --git a/8.c b/8.c
index aa46ec4..a400462 100644
--- a/8.c
+++ b/8.c
@@ -3,6 +3,7 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
+#include <unistd.h>
// Check if a tree is newly seen, by being taller than max or not
@@ -65,12 +66,65 @@ forest_seen(unsigned char * forest, int rows, int cols)
}
+// Get the maximum scenic score for a tree
int
-main()
+forest_maxscore(unsigned char * forest, int rows, int cols)
{
+ int i, j, max = 0;
+
+ for (i = 1; i < rows - 1; ++i) {
+ for (j = 1; j < cols - 2; ++j) {
+ int dist;
+ int score = 1;
+ int height = forest[i * cols + j];
+
+ for (dist = 1; j - dist > 0; ++dist)
+ if (forest[i * cols + j - dist] >= height)
+ break;
+ score *= dist;
+
+ for (dist = 1; j + dist < cols - 2; ++dist)
+ if (forest[i * cols + j + dist] >= height)
+ break;
+ score *= dist;
+
+ for (dist = 1; i - dist > 0; ++dist)
+ if (forest[(i - dist) * cols + j] >= height)
+ break;
+ score *= dist;
+
+ for (dist = 1; i + dist < rows - 1; ++dist)
+ if (forest[(i + dist) * cols + j] >= height)
+ break;
+ score *= dist;
+
+ if (score > max)
+ max = score;
+ }
+ }
+
+ return max;
+}
+
+
+int
+main(int argc, char ** argv)
+{
+ int i, part = 1;
int cols = 0, rows = 0;
char * forest;
+ while ((i = getopt(argc, argv, "p:")) != -1) {
+ switch (i) {
+ case 'p':
+ part = atoi(optarg);
+ break;
+
+ default:
+ return -1;
+ }
+ }
+
// Read first line
forest = malloc(BUFSIZ);
if (!fgets(forest, BUFSIZ, stdin)) {
@@ -115,7 +169,22 @@ main()
++rows;
}
- printf("Trees seen: %d\n", forest_seen((unsigned char *) forest, rows, cols));
+ switch (part) {
+ case 1:
+ printf("Trees seen: %d\n",
+ forest_seen((unsigned char *) forest, rows, cols));
+ break;
+
+ case 2:
+ printf("Best visibility: %d\n",
+ forest_maxscore((unsigned char *) forest, rows, cols));
+ break;
+
+ default:
+ fprintf(stderr, "Unexpected part %d\n", part);
+ free(forest);
+ return -1;
+ }
free(forest);