From 4074343756372a62a3e865c05ced3afe67d15ad1 Mon Sep 17 00:00:00 2001 From: pegeler <32426645+pegeler@users.noreply.github.com> Date: Mon, 9 Sep 2024 17:36:49 -0400 Subject: [PATCH] updated eddington.c --- c/eddington.c | 84 ++++++++++++++++++++++++++++++--------------------- 1 file changed, 49 insertions(+), 35 deletions(-) diff --git a/c/eddington.c b/c/eddington.c index 9e08da6..c355a8a 100644 --- a/c/eddington.c +++ b/c/eddington.c @@ -18,15 +18,52 @@ void usage(char *prog) { ); } -int main(int argc, char *argv[]) -{ - - FILE *file = stdin; - int is_stdin = 1; +/** Read lines from file stream and return them as an integer array + * + * @param[in] file the file stream to read from + * @param[out] n will be written with the number of values read in + */ +int *read_values(FILE *file, int *n) { char line[MAX_LEN]; int len = 1024; - int n, c, opt; int *r = malloc(len * sizeof(int)); + while (fgets(line, MAX_LEN, file) != NULL) { + if (*n >= len) { + len *= 2; + r = realloc(r, len * sizeof(int)); + } + r[(*n)++] = atoi(line); + } + return r; +} + +/** Compute the eddington number of an integer array and print the results + * + * @param[in] r the integer array to compute the Eddington number on + * @param[in] n the length of \p r + * @param[in] c whether to print the cumulative result + */ +void compute_eddington_number(int *r, int n, int c) { + int *h = calloc(n + 1, sizeof(int)); + + int E = 0; + for (int i=0, above=0; i < n; i++) { + if (r[i] > E) { + if (r[i] < n) h[r[i]]++; + if (++above > E) above -= h[++E]; + } + + if (c) /* Cumulative print */ + printf("%d\n", E); + } + + if (!c) /* Summary print if no cumulative */ + printf("%d\n", E); +} + +int main(int argc, char *argv[]) { + int *r; + int n, c, opt; n = c = opt = 0; @@ -50,41 +87,18 @@ int main(int argc, char *argv[]) } if (optind < argc && strncmp(argv[optind], "-", 1)) { - is_stdin = 0; + FILE *file; if ((file = fopen(argv[optind], "r")) == NULL) { fprintf(stderr, "Could not open file %s\n", argv[optind]); return EXIT_FAILURE; } + r = read_values(file, &n); + fclose(file); + } else { + r = read_values(stdin, &n); } - // Read in file - while (fgets(line, MAX_LEN, file) != NULL) { - if (n >= len) { - len *= 2; - r = realloc(r, len * sizeof(int)); - } - r[n++] = atoi(line); - } - - if (!is_stdin) fclose(file); - - // Initialize histogram - int *h = calloc(n + 1, sizeof(int)); - - // Run the algorithm - int E = 0; - for (int i=0, above=0; i < n; i++) { - if (r[i] > E) { - if (r[i] < n) h[r[i]]++; - if (++above > E) above -= h[++E]; - } - - if (c) /* Cumulative print */ - printf("%d\n", E); - } - - if (!c) /* Summary print if no cumulative */ - printf("%d\n", E); + compute_eddington_number(r, n, c); return EXIT_SUCCESS; }