# 
# After looking at some of the solutions, I altered my solution so that it 
# takes a lot less time and resource.
# 
# 
# 
# ---- Gosper4.pl ----
# --------------------
# - input a list of words
# - output questions and answers to STDOUT
# - usage: perl Gosper4.pl inputfilename > outputfilename
# - Ran with ActiveState Perl on Windoze
# - Lowercase all of the words of dictionary
# - Duplicate words will count as one entry
# - Allow any characters in word

use strict;
use warnings;

# Expect an argument for input dictionary
# ---------------------------------------
die "Usage: perl Gosper4.pl wordlistfile > outputfile\n" 
   unless (defined $ARGV[0] );

open Q, ">questions4" or die "Can't open 'questions4': $!\n";
open A, ">answers4" or die "Can't open 'answers4': $!\n";

my (%answer);
my ($question);

# Read dictionary and populate hash 
# -----------------------------------
while (<>) {
        chomp;
        my $wordlen = length;
        next if ($wordlen < 4);
        s/^\s+//;
        s/\s+$//;
        $_ = lc; #convert to all lowercase
        for (my $i=0; $i<=($wordlen-4); $i++) {
                $question = substr($_, $i, 4);
                unless ( exists $answer{$question} and $answer{$question} 
ne $_) {
                        $answer{$question} = $_;
                }
                else {
                        $answer{$question} = 1;
                }
        }
} 


# Output hash to STDOUT
# ----------------------
for $question ( sort keys %answer ) {
        unless ($answer{$question} eq "1" ) {
                print Q "$question\n";
                print A "$answer{$question}\n";
        }
}

__END__
