/* -*- mode: c -*-
* $Id: wordfreq.gcc,v 1.4 2001/01/07 19:24:51 doug Exp $
* http://www.bagley.org/~doug/shootout/
*/
#include <stdio.h>
#include <ctype.h>
#include <malloc.h>
#include <stdlib.h>
#include <string.h>
#define inline
#include "simple_hash.h"
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) ? strcmp((*b)->key, (*a)->key) : val);
}
int main() {
int bufsize = 80;
char *buf = (char *)malloc(bufsize + 1);
char c;
int i = 0;
struct ht_ht *ht = ht_create(75000);
struct ht_node **sort_array, **sort_tmp, *node;
while ((c = getchar()) > 0) {
if (isalpha(c)) {
buf[i++] = tolower(c);
if (i == bufsize) {
bufsize *= 2;
buf = realloc(buf, bufsize + 1);
}
} else {
if (i > 0) {
buf[i] = '\0';
++(ht_find_new(ht, buf)->val);
i = 0;
}
}
}
free(buf);
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<ht_count(ht); i++)
printf("%7d\t%s\n", ht_val(sort_array[i]), ht_key(sort_array[i]));
ht_destroy(ht);
return(0);
}