wf1.0 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. /* wf1 - print word frequencies; uses structures */
  2. struct node {
  3. int count; /* frequency count */
  4. struct node *left; /* left subtree */
  5. struct node *right; /* right subtree */
  6. char *word; /* word itself */
  7. } words[2000];
  8. int next; /* index of next free entry in words */
  9. struct node *lookup();
  10. main()
  11. {
  12. struct node *root;
  13. char word[20];
  14. root = 0;
  15. next = 0;
  16. while (getword(word))
  17. lookup(word, &root)->count++;
  18. tprint(root);
  19. return 0;
  20. }
  21. /* err - print error message s and die */
  22. err(s)
  23. char *s;
  24. {
  25. printf("? %s\n", s);
  26. exit(1);
  27. }
  28. /* getword - get next input word into buf, return 0 on EOF */
  29. int getword(buf)
  30. char *buf;
  31. {
  32. char *s;
  33. int c;
  34. while ((c = getchar()) != -1 && isletter(c) == 0)
  35. ;
  36. for (s = buf; c = isletter(c); c = getchar())
  37. *s++ = c;
  38. *s = 0;
  39. if (s > buf)
  40. return (1);
  41. return (0);
  42. }
  43. /* isletter - return folded version of c if it is a letter, 0 otherwise */
  44. int isletter(c)
  45. int c;
  46. {
  47. if (c >= 'A' && c <= 'Z')
  48. c += 'a' - 'A';
  49. if (c >= 'a' && c <= 'z')
  50. return (c);
  51. return (0);
  52. }
  53. /* lookup - lookup word in tree; install if necessary */
  54. struct node *lookup(word, p)
  55. char *word;
  56. struct node **p;
  57. {
  58. int cond;
  59. char *malloc();
  60. if (*p) {
  61. cond = strcmp(word, (*p)->word);
  62. if (cond < 0)
  63. return lookup(word, &(*p)->left);
  64. else if (cond > 0)
  65. return lookup(word, &(*p)->right);
  66. else
  67. return *p;
  68. }
  69. if (next >= 2000)
  70. err("out of node storage");
  71. words[next].count = 0;
  72. words[next].left = words[next].right = 0;
  73. words[next].word = malloc(strlen(word) + 1);
  74. if (words[next].word == 0)
  75. err("out of word storage");
  76. strcpy(words[next].word, word);
  77. return *p = &words[next++];
  78. }
  79. /* tprint - print tree */
  80. tprint(tree)
  81. struct node *tree;
  82. {
  83. if (tree) {
  84. tprint(tree->left);
  85. printf("%d\t%s\n", tree->count, tree->word);
  86. tprint(tree->right);
  87. }
  88. }
  89. /* strcmp - compare s1 and s2, return <0, 0, or >0 */
  90. int strcmp(s1, s2)
  91. char *s1, *s2;
  92. {
  93. while (*s1 == *s2) {
  94. if (*s1++ == 0)
  95. return 0;
  96. ++s2;
  97. }
  98. if (*s1 == 0)
  99. return -1;
  100. else if (*s2 == 0)
  101. return 1;
  102. return *s1 - *s2;
  103. }