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