#!/usr/bin/perl
###########################
#
# Example of reading from and doing a bit 
# of processing on a unix dictionary file.
#
# In class as a group exercise :
#
#  (1) Explain what the following code is doing, line by line.
#      Add some comments.
#
#  (2) Turn this into a perl object oriented class which can be 
#      called from other perl programs.
#
#      Here's the desired functionality :
#
#        use Dictionary;
#        my $dict = Dictionary->new();
#        print " 'foo' is a word\n" if $dict->lookup('foo');
#        my $random_word = $dict->random();
#        my $random_three_letter_word = $dict->random(3);
#
#  (3) To do so, 
#       * start with "h2xs -AXn Dictionary"
#       * remove the export stuff from Dictionary.pm
#       * keep adding to the POD, Changelog, Readme
#       * add tests to t/1.t with "ok()" functions  
#       * (Read about Test::More; Google will find it for you.)
#
#  (4) Some things to think about
#       * read in the system dictionary and store it first for perfomance ?
#       * get lists of 2, 3, ... 10 or so letter words first ?
#
# Thinking about this is motivated in part by
# the project that Daniel's thinking about, namely
# trying to decode things like what's produced
# by simple_encode.pl :
#    my $plain = "Hi there boys and girls.  Are we having fun yet?";
#    (my $coded = $plain) =~ tr/a-zA-Z/d-za-cD-ZA-C/;
#    print "plain: '$plain'.\n";
#    print "coded: '$coded'.\n";
#
# version 0.1
# Jim Mahoney at 1am on Nov 20 2003
###########################
use strict;
use warnings;
my $dict_file = "/usr/share/dict/words";
my $words_to_print = 10;
my $doubles        = 0;
my $doubledoubles  = 0;
my $tripledoubles  = 0;
my $word_number    = 0;
my @print_list;
my @triples;
open DICT, $dict_file or die "Can't open words: $!\n";
local $|=1;   # flush output buffer; i.e. don't wait for "/n" to print.
print "Looking at dictionary file '$dict_file' ... ";
while (my $word = <DICT>){
  $word_number++;
  chomp $word;
  for ($word){
    $doubles++                            if  /(\w)\1/;
    $doubledoubles++                      if  /(\w)\1.*(\w)\2/;
    $tripledoubles++, push @triples,$word if  /(\w)\1.*(\w)\2.*(\w)\3/;
  }
  next unless $word_number < $words_to_print;
  push @print_list, $word;
}
close DICT;
print "done.
 Total number of words = $word_number.
 Number with a repeated sequential letter = $doubles.
 Number with two repeated sequential letters = $doubledoubles.
 Number with three repeated sequential letters = $tripledoubles.
 First $words_to_print words are :
  @print_list
 Triple doubles : @triples
";
