in Doing Books

The C Programming Language (TCPL): Chapter 6

Exercise 6-4. Write a program that prints a distinct words in its input sorted into decreasing order of frequency of occurrence. Precede each word by its count.

#include
#include
#include

#define MAXWORDS 1024
#define MAXLENGTH 512

struct word {
char *name;
int count;
};

struct word wordlist[MAXWORDS];
int wordn = 0;

/* prototypes */
char *allocword(char *str);
int isword(char *str);
void addword(char *str);
int wordcmp(const void *a, const void *b);
void printwords();

int main()
{

char inputbuff[MAXLENGTH];
char tmpbuff[MAXLENGTH];
char *tmp;

while(fgets(inputbuff, MAXLENGTH, stdin) != NULL)
{

int i, k;
for(i = 0; inputbuff[i] != ''; i++)
{
if((inputbuff[i] == ' ' || inputbuff[i] == 't' || inputbuff[i] == 'n') && k != 0)
{
tmp = allocword(tmpbuff);
if(tmp == NULL)
{
printf("Error: Can't allocate enough space.n");
return 1;
}
strlcpy(tmp, tmpbuff, strlen(tmpbuff) + 1);
addword(tmp);
k = 0;
}
else
{
tmpbuff[k++] = inputbuff[i];
tmpbuff[k] = '';
}
}
}

printwords();
return 0;
}

char *allocword(char *str)
{
return (char *)malloc(sizeof(char) * (strlen(str) + 1));
}

int isword(char *str)
{
int i;
for(i = 0; i < wordn; i++) { if(!strncmp(wordlist[i].name, str, strlen(str))) { return i; } } return -1; } void addword(char *str) { int index; if((index = isword(str)) >= 0)
{
wordlist[index].count += 1;
} else {
wordlist[wordn].name = str;
wordlist[wordn].count = 1;
wordn++;
}

}

int wordcmp(const void *a, const void *b)
{
struct word *fst = (struct word *)a;
struct word *snd = (struct word *)b;

return -(fst->count - snd->count);
}

void printwords()
{
int i;

qsort(wordlist, wordn, sizeof(struct word), wordcmp);
for(i = 0; i < wordn; i++) { printf("%3i | %sn", wordlist[i].count, wordlist[i].name); } }

Write a Comment

Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.