Ejemplo n.º 1
0
 /**
  * Counts the number of distinct words in the input stream and then
  * prints a table of the words and the number of occurrences
  * on the output stream.
  * Uses a hash table.
  *
  * @param resource $in The input stream.
  * @param resource $out The output stream.
  */
 public static function wordCounter($in, $out)
 {
     $table = new ChainedHashTable(1031);
     while (($line = fgets($in)) != false) {
         $words = preg_split('/[ \\t\\n]+/', $line, -1, PREG_SPLIT_NO_EMPTY);
         foreach ($words as $word) {
             $assoc = $table->find(new Association(box($word)));
             if ($assoc === NULL) {
                 $table->insert(new Association(box($word), box(1)));
             } else {
                 $count = unbox($assoc->getValue());
                 $assoc->setValue(box($count + 1));
             }
         }
     }
     fprintf($out, "%s\n", str($table));
 }