home *** CD-ROM | disk | FTP | other *** search
/ Gold Fish 3 / goldfish_volume_3.bin / files / dev / c / cweb / examples / commonwords.w < prev    next >
Encoding:
Text File  |  1994-11-09  |  26.1 KB  |  704 lines

  1. % COMMONWORDS example of WEB/CWEB portability.  This documentation was
  2. % originally published in the ``Communications of the ACM'', Volume 29,6
  3. % (June 1986), and later in the book ``Literate Programming'', October 1991,
  4. % where it appeared as an example of WEB programming for Pascal by Donald
  5. % E. Knuth.  It has been translated into CWEB by Andreas Scherer to show
  6. % the ease of portability between Pascal/WEB and C/CWEB.  As little changes
  7. % as possible were made, so that the module numbering of the Pascal and
  8. % the C versions are virtually identical.  Restrictions of Pascal mentioned
  9. % in the WEB source were removed and the features of C were used instead.
  10.  
  11. % This program is distributed WITHOUT ANY WARRANTY, express or implied.
  12. % WEB Version --- Don Knuth, 1984
  13. % CWEB Version --- Andreas Scherer, 1993
  14.  
  15. \font\csc=cmcsc10
  16. \def\PASCAL/{{\csc Pascal\spacefactor1000}}
  17.  
  18. \def\title{COMMONWORDS (C Version 1.1)}
  19. \def\topofcontents{\null\vfill
  20.   \centerline{\titlefont Counting common word frequencies}
  21.   \vskip15pt
  22.   \centerline{(C Version 1.1)}
  23.   \vfill}
  24.  
  25. @* Introduction.  The purpose of this program is to solve the following
  26. problem posed by Jon Bentley@^Bentley, Jon Louis@>:
  27.  
  28. {\narrower\noindent Given a text file and an integer $k$, print the $k$
  29. most common words in the file (and the number of their occurrences) in
  30. decreasing frequency.\par}
  31.  
  32. Jon intentionally left the problem somewhat vague, but he stated that ``a
  33. user should be able to find the one hundred most frequent words in a
  34. twenty-page technical paper (roughly a 50K byte file) without undue
  35. emotional trauma.''
  36.  
  37. Let us agree that a {\it word\/} is a sequence of one or more contiguous
  38. letters; \.{"Bentley"} is a word, but \.{"ain't"} isn't.  The sequence
  39. of letters should be maximal, in the sense that it cannot be lengthened
  40. without including a nonletter.  Uppercase letters are considered equivalent
  41. to their lowercase counterparts, so that the words \.{"Bentley"} and
  42. \.{"BENTLEY"} and \.{"bentley"} are essentially identical.
  43.  
  44. The given problem still isn't well defined, for the file might contain more
  45. than $k$ words, all of the same frequency; or there might not even be as
  46. many as $k$ words.  Let's be more precise:  The most common words are to be
  47. printed in order of decreasing frequency, with words of equal frequency
  48. listed in alphabetic order.  Printing should stop after $k$ words have been
  49. output, if more than $k$ words are present.
  50.  
  51. @ The |stdin| file is assumed to contain the given text.  If it
  52. begins with a positive decimal number (preceded by optional blanks), that
  53. number will be the value of $k$; otherwise we shall assume that $k=100$.
  54. Answers will be sent to the |stdout| file.
  55.  
  56. @d default_k 100 /* use this value if $k$ isn't otherwise specified */
  57.  
  58. @ Besides solving the given problem, this program is supposed to be an
  59. example of the \.{CWEB} system, for people who know some \CEE/ but who
  60. have never seen \.{CWEB} before.  Here is an outline of the program to be
  61. constructed:
  62. @^Differences between \PASCAL/ and \CEE/@>
  63.  
  64. @d FALSE 0
  65. @d TRUE 1
  66.  
  67. @c
  68. #include <stdio.h>
  69. #include <stdlib.h>
  70.  
  71. typedef unsigned char boolean; /* for logical switches */
  72. @<Type declarations@>@/
  73. @<Global variables@>@/
  74. @<Procedures for initialization@>@/
  75. @<Procedures for input and output@>@/
  76. @<Procedures for data manipulation@>@/
  77. @<The main program@>@/
  78.  
  79. @ The main idea of the \.{CWEB} approach is to let the program grow in
  80. natural stages, with its parts presented in roughly the order that they
  81. might have been written by a programmer who isn't especially clairvoyant.
  82.  
  83. For example, each global variable will be introduced when we first know
  84. that it is necessary or desirable; the \.{CWEB} system will take care of
  85. collecting these declarations into the proper place.  We already know about
  86. one global variable, namely the number that Bentley called $k$.  Let us
  87. give it the more descriptive name |max_words_to_print|.
  88.  
  89. @<Global variables@>=
  90. unsigned int max_words_to_print; /* at most this many words will be printed */
  91.  
  92. @ As we introduce new global variables, we'll often want to give them
  93. certain starting values.  This will be done by the |initialize| procedure,
  94. whose body will consist of various pieces of code to be specified when we
  95. think of particular kinds of initialization.
  96.  
  97. @<Procedures for initialization@>=
  98. void initialize(void)
  99.    {
  100.    int i; /* all-purpose index for initializations */
  101.  
  102.    @<Set initial values@>@;
  103.    }
  104.  
  105. @ The \.{CWEB} system, which may be thought of as a preprocessor for
  106. \CEE/, includes a macro definition facility so that portable programs are
  107. easier to write.  For example, we have already defined `|default_k|' to be
  108. 100.  Here are two more examples of \.{CWEB} macros; they allow us to
  109. write, e.g., `|incr(count[p])|' as a convenient abbreviation for the
  110. statement `|count[p]=count[p]+1|'.
  111.  
  112. @d incr(A) ++A /* increment a variable */
  113. @d decr(A) --A /* decrement a variable */
  114.  
  115. @ Originally this program was written in the \PASCAL/ \.{WEB} language.
  116. In difference to \CEE/, \PASCAL/ uses labels and |goto| statements when
  117. abrupting procedures.  This isn't necessary for \CEE/ programs; they
  118. already know the |return| command, so this program will be totally
  119. |goto|-free.
  120. @^Differences between \PASCAL/ and \CEE/@>
  121.  
  122. @* Strategic considerations.  What algorithms and data structures should be
  123. used for Bentley's problem?  Clearly we need to be able to recognize
  124. different occurrences of the same word, so some sort of internal dictionary
  125. is necessary.  There's no obvious way to decide that a particular word of
  126. the input cannot possibly be in the final set, until we've gotten very near
  127. the end of the file; so we might as well remember every word that appears.
  128.  
  129. There should be a frequency count associated with each word, and we will
  130. eventually want to run through the words in order of decreasing frequency.
  131. But there's no need to keep these counts in order as we read through the
  132. input, since the order matters only at the end.
  133.  
  134. Therefore it makes sense to structure our program as follows:
  135.  
  136. @<The main program@>=
  137. void main(void)
  138.    {
  139.    initialize();
  140.    @<Establish the value of |max_words_to_print|@>@;
  141.    @<Input the text, maintaining a dictionary with frequency counts@>@;
  142.    @<Sort the dictionary by frequency@>@;
  143.    @<Output the results@>@;
  144.    }
  145.  
  146. @* Basic input routines.  Let's switch to a bottom-up approach now, by
  147. writing some of the procedures that we know will be necessary sooner or
  148. later.  Then we'll have some confidence that our program is taking shape,
  149. even though we haven't decided yet how to handle the searching or the
  150. sorting.  It will be nice to get the messy details of \CEE/ input out of
  151. the way and off our minds.
  152.  
  153. Here's a function that reads an optional positive integer, returning zero
  154. if none is present at the beginning of the current line.
  155.  
  156. @<Procedures for input and output@>=
  157. int read_int(void)
  158.    {
  159.    int n=0; /* the accumulated value */
  160.    char c; /* the character from the input we're reading */
  161.  
  162.    if( (c=fgetc(stdin)) != EOF ) {
  163.       for(; (c=='\n') || (c==' ') || (c=='\t'); c=fgetc(stdin));
  164.       while(c>='0' && c<='9') {
  165.          n = 10*n + c - '0';
  166.          c=fgetc(stdin);
  167.          }
  168.       }
  169.    return(n);
  170.    }
  171.  
  172. @ We invoke |read_int| only once.
  173.  
  174. @<Establish the value of |max_words_to_print|@>=
  175.    max_words_to_print = read_int();
  176.    if(max_words_to_print==0)
  177.       max_words_to_print = default_k;
  178.  
  179. @ To find words in the |stdin| file, we want a quick way to distinguish
  180. letters from nonletters.  In contrary to \PASCAL/, \CEE/ makes this problem
  181. very easy, because we can fully rely on {\mc ASCII}.  We shall define an
  182. array, |lettercode|, which maps arbitrary characters into the integers
  183. $0\ldots26$.
  184. @^Differences between \PASCAL/ and \CEE/@>
  185.  
  186. If $c$ is a value of type |char| that represents the $k$th letter of the
  187. alphabet, then |lettercode[c]==k|; but if $c$ is a nonletter,
  188. |lettercode[c]==0|.  We assume that $0\leq c\leq255$ whenever $c$ is of
  189. type |char|, i.e., we are dealing with |unsigned char|.
  190.  
  191. @<Global variables@>=
  192. unsigned char lettercode[256]; /* the input conversion table */
  193.  
  194. @ The array |lettercode| is filled with $0$ for all non-letters, and with
  195. the number of the letter in the alphabet.  We won't distinguish between
  196. uppercase and lowercase letters in this program.
  197. @^Differences between \PASCAL/ and \CEE/@>
  198.  
  199. @<Set initial values@>=
  200.    for(i=0; i<=255; ++i)
  201.       lettercode[i]=0; /* non-letter */
  202.  
  203.    lettercode['a'] = lettercode['A'] = 1; @+
  204.    lettercode['b'] = lettercode['B'] = 2;
  205.    lettercode['c'] = lettercode['C'] = 3; @+
  206.    lettercode['d'] = lettercode['D'] = 4;
  207.    lettercode['e'] = lettercode['E'] = 5; @+
  208.    lettercode['f'] = lettercode['F'] = 6;
  209.    lettercode['g'] = lettercode['G'] = 7; @+
  210.    lettercode['h'] = lettercode['H'] = 8;
  211.    lettercode['i'] = lettercode['I'] = 9; @+
  212.    lettercode['j'] = lettercode['J'] = 10;
  213.    lettercode['k'] = lettercode['K'] = 11; @+
  214.    lettercode['l'] = lettercode['L'] = 12;
  215.    lettercode['m'] = lettercode['M'] = 13; @+
  216.    lettercode['n'] = lettercode['N'] = 14;
  217.    lettercode['o'] = lettercode['O'] = 15; @+
  218.    lettercode['p'] = lettercode['P'] = 16;
  219.    lettercode['q'] = lettercode['Q'] = 17; @+
  220.    lettercode['r'] = lettercode['R'] = 18;
  221.    lettercode['s'] = lettercode['S'] = 19; @+
  222.    lettercode['t'] = lettercode['T'] = 20;
  223.    lettercode['u'] = lettercode['U'] = 21; @+
  224.    lettercode['v'] = lettercode['V'] = 22;
  225.    lettercode['w'] = lettercode['W'] = 23; @+
  226.    lettercode['x'] = lettercode['X'] = 24;
  227.    lettercode['y'] = lettercode['Y'] = 25; @+
  228.    lettercode['z'] = lettercode['Z'] = 26;
  229.  
  230. @ Each new word found in the input will be placed into a |buffer| array.
  231. We shall assume that no words are more than $60$ letters long; if a longer
  232. word appears, it will be truncated to 60~characters, and a warning message
  233. will be printed at the end of the run.
  234.  
  235. @d max_word_length 60 /* words shouldn't be longer than this */
  236.  
  237. @<Global variables@>=
  238. unsigned char buffer[max_word_length]; /* the current word */
  239. unsigned int word_length; /* the number of active letters currently in |buffer|;
  240.    $0\ldots$|max_word_length| */
  241. boolean word_truncated; /* was some word longer than |max_word_length|?*/
  242.  
  243. @ @<Set initial values@>=
  244.    word_truncated=FALSE;
  245.  
  246. @ We're ready now for the main input routine, which puts the next word into
  247. the buffer.  If no more words remain, |word_length| is set to zero;
  248. otherwise |word_length| is set to the length of the new word.
  249.  
  250. @<Procedures for input and output@>=
  251. void get_word(void)
  252.    {
  253.    unsigned char c; /* the character we're currently reading */
  254.  
  255.    word_length=0;
  256.    if((c=fgetc(stdin))!=EOF) {
  257.       while(lettercode[c]==0)
  258.          if((c=fgetc(stdin))==EOF)
  259.             return;
  260.       @<Read a word into |buffer|@>@;
  261.       }
  262.    }
  263.  
  264. @ At this point |lettercode[c]>0|, hence $c$ contains the first letter of a
  265. word.
  266.  
  267. @<Read a word into |buffer|@>=
  268.    do @+ {
  269.       if(word_length==max_word_length)
  270.          word_truncated=TRUE;
  271.       else {
  272.          incr(word_length);
  273.          buffer[word_length-1]=lettercode[c];
  274.          }
  275.       c=fgetc(stdin);
  276.       } @+ while(lettercode[c]!=0);
  277.  
  278. @* Dictionary lookup.  Given a word in the buffer, we will want to look for
  279. it in a dynamic dictionary of all words that have appeared so far.  We
  280. expect many words to occur often, so we want a search technique that will
  281. find existing words quickly.  Furthermore, the dictionary should
  282. accommodate words of variable length, and (ideally) it should also
  283. facilitate the task of alphabetic ordering.
  284.  
  285. These constraints suggest a variant of the data structure introduced by
  286. Frank M. Liang@^Liang, Franklin Mark@> in his Ph.D. thesis [{\sl Word
  287. Hy-phen-a-tion by Com-pu-ter}, Stanford University, 1983].  Liang's
  288. structure, which we may call a {\it hash trie}, requires comparatively few
  289. operations to find a word that is already present, although it may take
  290. somewhat longer to insert a new entry.  Some space is sacrificed---we will
  291. need two pointers, a count, and another 5-bit field for each character in
  292. the dictionary, plus extra space to keep the hash table from becoming
  293. congested---but relatively large memories are commonplace nowadays, so the
  294. method seems ideal for the present application.
  295.  
  296. A trie represents a set of words and all prefixes of those words
  297. [cf.~Knuth@^Knuth, Donald Ervin@>, {\sl Sorting and Searching}, Section~6.3].
  298. For convenience, we shall say that all nonempty prefixes of the words in
  299. our dictionary are also words, even though they may not occur as ``words''
  300. in the input file.  Each word (in this generalized sense) is represented
  301. by a |pointer|, which is an index into four large arrays called |link|,
  302. |sibling|, |count|, and |ch|.
  303.  
  304. @d trie_size 32767 /* the largest pointer value */
  305.  
  306. @<Type declarations@>=
  307. typedef unsigned int pointer; /* $0\ldots$|trie_size| */
  308.  
  309. @ One-letter words are represented by the pointers $1$ through $26$.  The
  310. representation of longer words is defined recursively: If $p$ represents
  311. word $w$ and if $1\leq c\leq26$, then the word $w$ followed by the $c$th
  312. letter of the alphabet is represented by |link[p]+c|.
  313.  
  314. For example, suppose that |link[2]==1000|, |link[1005]==2000|, and
  315. |link[2014]==3000|.  Then the word \.{"b"} is represented by the pointer
  316. value~2; \.{"be"} is represented by |link[2]+5==1005|; \.{"ben"} is
  317. represented by~2014; and \.{"bent"} by~3020.  If no longer word beginning
  318. with \.{"bent"} appears in the dictionary, |link[3020]| will be zero.
  319.  
  320. The hash trie also contains redundant information to facilitate traversal
  321. and updating.  If |link[p]| is nonzero, then |link[link[p]]==p|.
  322. Furthermore if |q==link[p]+c| is a ``child'' of $p$, we have |ch[q]==c|;
  323. this additional information makes it possible to go from child to parent,
  324. since |link[q-ch[q]]==link[link[p]]==p|.
  325.  
  326. Children of the same parent are linked together cyclically by |sibling|
  327. pointers: The largest child of $p$ is |sibling[link[p]]|, and the next
  328. largest is |sibling[sibling[link[p]]]|; the smallest child's |sibling|
  329. pointer is |link[p]|.  Continuing our example, if all words in the
  330. dictionary beginning with \.{"be"} start with either \.{"ben"} or
  331. \.{"bet"}, then |sibling[2000]==2020|, |sibling[2020]==2014|, and
  332. |sibling[2014]==2000|.
  333.  
  334. Notice that children of different parents might appear next to each other.
  335. For example, we might have |ch[2019]==6|, for the child of some word such
  336. that |link[p]==2013|.
  337.  
  338. If |link[p]!=0|, the table entry in position |link[p]| is called the
  339. ``header'' of $p$'s children.  The special code value |header| appears in
  340. the |ch| field of each header entry.
  341.  
  342. If $p$ represents a word, |count[p]| is the number of times that the word
  343. has occurred in the input so far.  The |count| field in a header entry is
  344. undefined.
  345.  
  346. Unused positions $p$ have |ch[p]==empty_slot|.  In this case |link[p]|,
  347. |sibling[p]|, and |count[p]| are undefined.
  348.  
  349. @d empty_slot 0
  350. @d header 27
  351. @d move_to_prefix(A) A=link[A-ch[A]]
  352. @d move_to_last_suffix(A) while(link[A]!=0) A=sibling[link[A]]
  353.  
  354. @<Global variables@>=
  355. unsigned int link[trie_size+1],sibling[trie_size+1]; /* $0\ldots$|trie_size| */
  356. unsigned char ch[trie_size+1]; /* |empty_slot|$\ldots$|header| */
  357.  
  358. @ @<Set initial values@>=
  359.    for(i=27; i<=trie_size; ++i)
  360.       ch[i]=empty_slot;
  361.    for(i=1; i<=26; ++i) {
  362.       ch[i]=i; @+ link[i]=count[i]=0; @+ sibling[i]=i-1;
  363.       }
  364.    ch[0]=header; @+ link[0]=0; @+ sibling[0]=26;
  365.  
  366. @ Here's the basic subroutine that finds a given word in the dictionary.
  367. The word will be inserted (with a |count| of zero) if it isn't already
  368. present.
  369.  
  370. More precisely, the |find_buffer| function looks for the contents of
  371. |buffer|, and returns a pointer to the appropriate dictionary location.  If
  372. the dictionary is so full that a new word cannot be inserted, the pointer~$0$
  373. is returned.
  374.  
  375. @d abort_find return(0)
  376.  
  377. @<Procedures for data manipulation@>=
  378. unsigned int find_buffer(void) /* returns values from $0$ to |trie_size| */
  379.    {
  380.    unsigned int i; /* index into |buffer| with values from
  381.       $1$ to |max_word_length| */
  382.    unsigned int p; /* the current word position */
  383.    unsigned int q; /* the next word position */
  384.    unsigned char c; /* current letter code */
  385.    @<Other local variables of |find_buffer|@>@;@#
  386.  
  387.    i=1; @+ p=buffer[0];
  388.    while(i<word_length) {
  389.       incr(i); @+ c=buffer[i-1];
  390.       @<Advance |p| to its child number |c| @>@;
  391.       }
  392.    return(p);
  393.    }
  394.  
  395. @ @<Advance |p| to its child number |c|@>=
  396.    if(link[p]==0)
  397.       @<Insert the firstborn child of |p| and move to it, or |abort_find|@>@;
  398.    else {
  399.       q = link[p] + c;
  400.       if(ch[q] != c) {
  401.          if(ch[q] != empty_slot)
  402.             @<Move |p|'s family to a place where child |c| will fit,
  403.               or |abort_find|@>@;
  404.          @<Insert child |c| into |p|'s family@>@;
  405.          }
  406.       p = q;
  407.    }
  408.  
  409. @ Each ``family'' in the trie has a header location |h==link[p]| such that
  410. child |c| is in location |h+c|.  We want these values to be spread out in
  411. the trie, so that families don't often interfere with each other.
  412. Furthermore we will need to have $26<h\leq{}$|trie_size|${}-26$ if the
  413. search algorithm is going to work properly.
  414.  
  415. One of the main tasks of the insertion algorithm is to find a place for a
  416. new header.  The theory of hashing tells us that it is advantageous to put
  417. the |n|th header near the location $x_n=\alpha n\bmod t$, where
  418. $t={}$|trie_size|${}-52$ and where $\alpha$ is an integer relatively prime
  419. to $t$ such that $\alpha/t$ is approximately equal to the golden ratio
  420. $(\sqrt{5}-1)/2\approx.61803$.  [These locations $x_n$ are about as
  421. ``spread out'' as you can get; see {\sl Sorting and Searching},
  422. pp.~510--511.]
  423.  
  424. @d alpha 20219 /* $\approx.61803$|trie_size| */
  425.  
  426. @<Global variables@>=
  427. pointer x; /* $\alpha n \bmod ($|trie_size|${}-52)$ */
  428.  
  429. @ @<Set initial values@>=
  430.    x = 0;
  431.  
  432. @ We will give up trying to find a vacancy if 1000 trials have been made
  433. without success.  This will happen only if the table is quite full, at
  434. which time the most common words will probably already appear in the
  435. dictionary.
  436.  
  437. @d tolerance 1000
  438.  
  439. @<Get set for computing header locations@>=
  440.    if(x < trie_size - 52 - alpha)
  441.       x += alpha;
  442.    else
  443.       x += alpha - trie_size + 52;
  444.    h = x + 27; /* now $26<h\leq{}$|trie_size|${}-26$ */
  445.    if(h <= trie_size - 26 - tolerance)
  446.       last_h = h + tolerance;
  447.    else
  448.       last_h = h + tolerance - trie_size + 52;
  449.  
  450. @ @<Compute the next trial header location |h|, or |abort_find|@>=
  451.    if(h == last_h)
  452.       abort_find;
  453.    if(h == trie_size - 26)
  454.       h = 27;
  455.    else
  456.       incr(h);
  457.  
  458. @ @<Other local variables of |find_buffer|@>=
  459.    pointer h; /* trial header location */
  460.    int last_h; /* the final one to try */
  461.  
  462. @ @<Insert the firstborn child of |p| and move to it, or |abort_find|@>=
  463.    {
  464.    @<Get set for computing header locations@>@;
  465.    do @+ {
  466.       @<Compute the next trial header location |h|, or |abort_find|@>@;
  467.       } @+ while((ch[h] != empty_slot) || (ch[h+c] != empty_slot));
  468.    link[p] = h; @+ link[h] = p; @+p = h + c;
  469.    ch[h] = header; @+ ch[p] = c;
  470.    sibling[h] = p; @+ sibling[p] = h; @+ count[p] = link[p] = 0;
  471.    }
  472.  
  473. @ The decreasing order of |sibling| pointers is preserved here.  We assume
  474. that |q==link[p]+c|.
  475.  
  476. @<Insert child |c| into |p|'s family@>=
  477.    {
  478.    h = link[p];
  479.    while(sibling[h]>q)
  480.       h = sibling[h];
  481.    sibling[q] = sibling[h]; @+ sibling[h] = q;
  482.    ch[q] = c; @+ count[q] = link[q] = 0;
  483.    }
  484.  
  485. @ There's one complicated case, which we have left for last.  Fortunately
  486. this step doesn't need to be done very often in practice, and the families
  487. that need to be moved are generally small.
  488.  
  489. @<Move |p|'s family to a place where child |c| will fit, or |abort_find|@>=
  490.    {
  491.    @<Find a suitable place |h| to move, or |abort_find|@>@;
  492.    q = h+c; @+ r = link[p]; @+ delta = h-r;
  493.    do @+ {
  494.       sibling[r+delta] = sibling[r] + delta;
  495.       ch[r+delta] = ch[r];
  496.       ch[r] = empty_slot;
  497.       count[r+delta] = count[r];
  498.       link[r+delta] = link[r];
  499.       if(link[r] != 0)
  500.          link[link[r]] = r + delta;
  501.       r = sibling[r];
  502.       } @+ while(ch[r] != empty_slot);
  503.    }
  504.  
  505. @ @<Other local variables of |find_buffer|@>=
  506.    pointer r; /* family member to be moved */
  507.    int delta; /* amount of motion */
  508.    boolean slot_found; /* have we found a new homestead? */
  509.  
  510. @ @<Find a suitable place |h| to move, or |abort_find|@>=
  511.    slot_found = FALSE;
  512.    @<Get set for computing header locations@>@;
  513.    do @+ {
  514.       @<Compute the next trial header location |h|, or |abort_find|@>@;
  515.       if(ch[h+c] == empty_slot) {
  516.          r = link[p];
  517.          delta = h-r;
  518.          while((ch[r+delta]==empty_slot) && (sibling[r]!=link[p]))
  519.             r = sibling[r];
  520.          if(ch[r+delta] == empty_slot)
  521.             slot_found = TRUE;
  522.          }
  523.       } @+ while(!slot_found);
  524.  
  525. @* The frequency counts.  It is, of course, a simple matter to combine
  526. dictionary lookup with the |get_word| routine, so that all the word
  527. frequencies are counted.  We may have to drop a few words in extreme cases
  528. (when the dictionary is full or the maximum count has been reached).
  529.  
  530. @d max_count 32767 /* counts won't go higher than this */
  531.  
  532. @<Global variables@>=
  533.    int count[trie_size+1];
  534.    boolean word_missed; /* did the dictionary get too full? */
  535.    pointer p; /* location of the current word */
  536.  
  537. @ @<Set initial values@>=
  538.    word_missed = FALSE;
  539.  
  540. @ @<Input the text, maintaining a dictionary with frequency counts@>=
  541.    get_word();
  542.    while(word_length) {
  543.       if((p = find_buffer()) == NULL)
  544.          word_missed = TRUE;
  545.       else if(count[p] < max_count)
  546.          incr(count[p]);
  547.       get_word();
  548.       }
  549.  
  550. @ While we have the dictionary structure in mind, let's write a routine
  551. that prints the word corresponding to a given pointer, together with the
  552. corresponding frequency count.
  553.  
  554. For obvious reasons, we put the word into the buffer backwards during this
  555. process.
  556.  
  557. As we can rely on the relative order of the characters in the {\mc ASCII}
  558. set, no conversion array is needed here.  Simple arithmetic will suffice.
  559. @^Differences between \PASCAL/ and \CEE/@>
  560.  
  561. @<Procedures for input and output@>=
  562. void print_word(pointer p)
  563.    {
  564.    pointer q; /* runs through ancestors of |p| */
  565.    unsigned int i; /* index into |buffer|; $1\ldots{}$|max_word_length| */
  566.  
  567.    word_length = 0; @+ q = p; @+ fputc(' ',stdout);
  568.    do @+ {
  569.       incr(word_length);
  570.       buffer[word_length-1] = ch[q];
  571.       move_to_prefix(q);
  572.       } @+ while(q != 0);
  573.    for(i=word_length; i>=1; --i)
  574.       fputc(buffer[i-1]-1+'a',stdout);
  575.    if(count[p] < max_count)
  576.       fprintf(stdout," %d\n",count[p]);
  577.    else
  578.       fprintf(stdout," %d or more\n",max_count);
  579.    fflush(stdout);
  580.    }
  581.  
  582. @* Sorting a trie.  Almost all of the frequency counts will be small, in
  583. typical situations, so we needn't use a general-purpose sorting method.  It
  584. suffices to keep a few linked lists for the words with small frequencies,
  585. with one other list to hold everything else.
  586.  
  587. @d large_count 200 /* smaller counts are in separate lists */
  588.  
  589. @<Global variables@>=
  590. pointer sorted[large_count]; /* list heads */
  591. unsigned int total_words; /* the number of words sorted */
  592.  
  593. @ If we walk through the trie in reverse alphabetical order, it is a simple
  594. matter to change the sibling links so that the words of frequency |f| are
  595. pointed to by |sorted[f-1]|, |sibling[sorted[f-1]]|, $\ldots$ in alphabetical
  596. order.  When |f==large_count|, the words must also be linked in decreasing
  597. order of their |count| fields.
  598.  
  599. The restructuring operations are slightly subtle here, because we are
  600. modifying the |sibling| pointers while traversing the trie.
  601.  
  602. @<Procedures for data manipulation@>=
  603. void trie_sort(void)
  604.    {
  605.    unsigned int k; /* index to |sorted|; $1\ldots{}$|large_count| */
  606.    pointer p; /* current position in the trie */
  607.    unsigned int f; /* current frequency count; $0\ldots{}$|max_count| */
  608.    pointer q, r; /* list manipulation variables */
  609.  
  610.    total_words = 0;
  611.    for(k=1; k<=large_count; ++k)
  612.       sorted[k-1] = 0;
  613.    p = sibling[0]; @+ move_to_last_suffix(p);
  614.    do @+ {
  615.       f = count[p]; @+ q = sibling[p];
  616.       if(f)
  617.          @<Link |p| into the list |sorted[f-1]|@>@;
  618.       if(ch[q] != header) {
  619.          p = q; @+ move_to_last_suffix(p);
  620.          }
  621.       else
  622.          p = link[q]; /* move to prefix */
  623.       } @+ while(p);
  624.    }
  625.  
  626. @ Here we use the fact that |count[0]==0|.
  627.  
  628. @<Link |p| into the list |sorted[f-1]|@>=
  629.    {
  630.    incr(total_words);
  631.    if(f < large_count) { /* easy case */
  632.       sibling[p] = sorted[f-1]; @+ sorted[f-1] = p;
  633.       }
  634.    else {
  635.       r = sorted[large_count-1];
  636.       if(count[p] >= count[r]) {
  637.          sibling[p] = r; @+ sorted[large_count-1] = p;
  638.          }
  639.       else {
  640.          while(count[p] < count[sibling[r]])
  641.             r = sibling[r];
  642.          sibling[p] = sibling[r]; @+ sibling[r] = p;
  643.          }
  644.       }
  645.    }
  646.  
  647. @ @<Sort the dictionary by frequency@>=
  648.    trie_sort();
  649.  
  650. @ After |trie_sort| has done its thing, the sequence of linked lists
  651. |sorted[large_count-1]|, $\ldots$, |sorted[0]| collectively contain all the
  652. words of the input file, in decreasing order of frequency.  Words of equal
  653. frequency appear in alphabetic order.  The individual lists are linked by
  654. means of the |sibling| array.
  655.  
  656. Therefore the following procedure will print the first |k| words, as
  657. required in Bentley's problem.
  658.  
  659. @<Procedures for input and output@>=
  660. void print_common(int k)
  661.    {
  662.    unsigned int f; /* current frequency */
  663.    pointer p; /* current or next word */
  664.  
  665.    f = large_count; @+ p = sorted[f-1];
  666.    do @+ {
  667.       while(p == 0) {
  668.          if(f==1)
  669.             return;
  670.          decr(f); @+ p = sorted[f-1];
  671.          }
  672.       print_word(p); @+ decr(k); @+ p = sibling[p];
  673.       } @+ while(k>0);
  674.    }
  675.  
  676. @* The endgame.  We have recorded |total_words| different words.
  677. Furthermore the global variables |word_missed| and |word_truncated| tell
  678. whether or not any storage limitations were exceeded.  So the remaining
  679. task is simple:
  680.  
  681. @<Output the results@>=
  682.    if(total_words == 0)
  683.       fputs("There are no words in the input!\n",stdout);
  684.    else {
  685.       if(total_words < max_words_to_print) /* we will print all words */
  686.          fputs("Words of the input file, ordered by frequency: \n",stdout);
  687.       else if(max_words_to_print == 1)
  688.          fputs("The most common word and its frequency: \n",stdout);
  689.       else
  690.          fprintf(stdout,"The %d most common words, and their frequencies: \n",
  691.             max_words_to_print);
  692.       print_common(max_words_to_print);
  693.       if(word_truncated)
  694.          fprintf(stdout,"(At least one word had to be shortened to %d letters.)\n",
  695.             max_word_length);
  696.       if(word_missed)
  697.          fputs("(Some input data was skipped, due to memory limitations.)\n",
  698.             stdout);
  699.       }
  700.    fflush(stdout);
  701.  
  702. @* Index.  Here is a list of all uses of all identifiers, underlined at the
  703. point of definition.
  704.