Skip to content

Commit

Permalink
updated eddington.c
Browse files Browse the repository at this point in the history
  • Loading branch information
pegeler committed Sep 9, 2024
1 parent d01e5f2 commit 4074343
Showing 1 changed file with 49 additions and 35 deletions.
84 changes: 49 additions & 35 deletions c/eddington.c
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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;
}

0 comments on commit 4074343

Please sign in to comment.