/* -*- mode: c -*- * $Id: wordfreq.gcc,v 1.5 2001/09/18 17:25:18 doug Exp $ * http://www.bagley.org/~doug/shootout/ * Changed by Adrian Merrill 2001/08/22 */ #include #include #include #include #include #include "../../Include/simple_hash.h" #define QUICKIE_STRCMP(a, b) (*(a) != *(b) ? *(a) - *(b) : strcmp((a), (b))) typedef int (*comparator)(const void *, const void *); int cmp_hash(struct ht_node **a, struct ht_node **b) { int val = (*b)->val - (*a)->val; return((val == 0) ? QUICKIE_STRCMP((*b)->key, (*a)->key) : val); } int main() { int readbufsize = 4096; int wordbufsize=16; char *readbuf = (char *)malloc(readbufsize + 1); char *wordbuf = (char *)malloc(wordbufsize + 1); int i = 0; struct ht_ht *ht = ht_create(2048); struct ht_node **sort_array, **sort_tmp, *node; /*new code*/ int nread =0; int wordlen=0; readbuf[0]=0; while (readbuf[i] > 0||(nread = fread(readbuf, sizeof(char), readbufsize, stdin),readbuf[nread] = '\0',i=0,nread > 0) ) { if (isalpha(readbuf[i])){ wordbuf[wordlen++] = tolower(readbuf[i]); if (wordlen == wordbufsize) { wordbufsize *= 2; wordbuf = realloc(wordbuf, wordbufsize + 1); } } else{ if (wordlen > 0) { wordbuf[wordlen] = '\0'; ++(ht_find_new(ht, wordbuf)->val); wordlen = 0; } } i++; } free(readbuf); free(wordbuf); sort_array = sort_tmp = malloc(sizeof(struct ht_node *) * ht_count(ht)); for (node=ht_first(ht); (*sort_tmp++ = node) != 0; node=ht_next(ht)) ; qsort(sort_array, ht_count(ht), sizeof(struct ht_node *), (comparator)cmp_hash); for (i=0; i