From 631fe6892464c8b41cbff5ee1785ade2c24986c6 Mon Sep 17 00:00:00 2001 From: Adam Spragg Date: Thu, 8 Dec 2022 18:34:30 +0000 Subject: Solve puzzle 8 part 2 --- 8.c | 73 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file 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 #include #include +#include // 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); -- cgit v1.2.1