From a7096903fdf611a58466946456587820696bc62f Mon Sep 17 00:00:00 2001 From: Adam Spragg Date: Wed, 7 Dec 2022 20:05:32 +0000 Subject: Solve puzzle 7 part 2 --- 7.c | 48 ++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 40 insertions(+), 8 deletions(-) diff --git a/7.c b/7.c index d19b51d..cb41168 100644 --- a/7.c +++ b/7.c @@ -4,6 +4,7 @@ #include #include #include +#include //#define DENT_DUMP @@ -266,13 +267,24 @@ cmd_cd(struct dent ** cwd, char * buf, size_t bufsiz, FILE * in, char const * ar int -main() +main(int argc, char ** argv) { char buf[BUFSIZ]; struct dent * cwd = NULL, * root, * d; - int i; + int i, part = 1; size_t s; + while ((i = getopt(argc, argv, "p:")) != -1) { + switch (i) { + case 'p': + part = atoi(optarg); + break; + + default: + return -1; + } + } + i = fgets(buf, sizeof(buf), stdin) ? 0 : -1; while (i == 0) { char * tok, * toksave = NULL; @@ -316,13 +328,33 @@ main() // Calculate disk usage sizes; dent_du(root); - // Find directories whose size is less than a limit, and sum them. - s = 0; - for (d = root; d != NULL; d = dent_next(d)) { - if (d->type == DT_DIR && d->size <= 100000) - s += d->size; + switch (part) { + case 1: + // Find directories whose size is less than a limit, and sum them. + s = 0; + for (d = root; d != NULL; d = dent_next(d)) { + if (d->type == DT_DIR && d->size <= 100000) + s += d->size; + } + printf("Sum of dir sizes where size <= 100000: %zu\n", s); + break; + + case 2: + // Find smallest directory to delete that drops disk space to 70M - 30M + s = 70000000; + for (d = root; d != NULL; d = dent_next(d)) { + if (d->type == DT_DIR + && d->size < s + && root->size - d->size < 40000000) + s = d->size; + } + printf("Smallest dir that can drop usage below 40000000: %zu\n", s); + break; + + default: + fprintf(stderr, "Unexpected part %d\n", part); + return -1; } - printf("Sum of dir sizes where size <= 100000: %zu\n", s); // Tidy up dent_free(root); -- cgit v1.2.1