#include "header.h" /* comparison function needed for quicksort -- sorts * backwards */ int compare (const void * a, const void * b) { struct dfreq *a1, *b1; a1 = (struct dfreq *) a; b1 = (struct dfreq *) b; return (b1->count - a1->count); } /* zero the multi-dim array before main logic */ int zero (long arr[SIZE][SIZE]) { int i, j; for (i = 0; i < SIZE; i++) { for (j = 0; j < SIZE; j++) { arr[i][j] = 0; } } return 0; } /* move multi-dimensional array data to a dfreq array */ int transfer (long arr[SIZE][SIZE]) { int i, j, k; /* transfer multi-dim array data to struct array */ k = 0; for (int i = 0; i < SIZE; i++) { for (int j = 0; j < SIZE; j++) { pd[k].code1 = i; pd[k].code2 = j; pd[k].count = arr[i][j]; k++; } } return 0; } int main (int argc, char *argv[]) { long array[SIZE][SIZE]; FILE *fp; int i, sqrsize = SIZE*SIZE; unsigned char uc[NMax+1]; // TODO: why NMax + 1 ? char Format[20]; // store formating info for scanf sprintf(Format, "%%%dc", NMax); clock_t start, stop; start = clock(); zero(array); /* file reading logic! */ fp = fopen(argv[1], "r"); /* In order to change the number of characters being read * at once through fscanf, I have made the following logic * execute once and then start looping if there are more * characters in the file. The initial case is different * than the following cases because there is no clast to * deal with. */ int c1, c2, clast, nchar; // current character ascii values /* open file for reading, send data to multi-dim array */ if (fscanf(fp, Format, uc) > 0) { nchar = strlen(uc); clast = uc[nchar-1]; c1 = uc[0]; for (i = 1; i < nchar; i++) { c2 = uc[i]; array[c1][c2]++; c1 = c2; } } while (fscanf(fp, Format, uc) > 0) { nchar = strlen(uc); // store number of chars taken this loop c1 = uc[0]; array[clast][c1]++; // add character pairs between fscans clast = uc[nchar-1]; // store last char from this loop for (i = 1; i < nchar; i++) { c2 = uc[i]; array[c1][c2]++; c1 = c2; } } fclose(fp); transfer(array); qsort (pd, sqrsize, sizeof(struct dfreq), compare); /* print NOut most frequent dipthongs */ for (i = 0; i < NOut; i++) { int c1 = pd[i].code1; int c2 = pd[i].code2; if (isprint(c1) && isprint(c2)) { printf("(%3d,%3d) %c%c %d\n", c1, c2, c1, c2, pd[i].count); } else { printf("(%3d,%3d) %d\n", c1, c2, pd[i].count); } } stop = clock(); printf("\nElapsed time = %g Seconds\n", (stop-start)/((float) CLOCKS_PER_SEC)); return 0; }