#!/usr/local/bin/perl

use strict;
use warnings;

our %answers;

WORD: while (my $word = <>) {
    chomp $word;

    for (my $i = 0;; $i++) {
	# the spec refers to "every sequence of four letters"
	# I interpret that to mean that 'A' and 'a' are the same
	# *letter*, even though they're different characters, so
	# let's always compare all-lowercase strings
	my $question = lc (substr ($word, $i, 4));

	# there are two ways we can end up with a question that's
	# shorter than 4 letters: (1) the initial word might be shorter
	# than 4 letters, or (2) the remainder of the string is less than
	# 4 letters
	next WORD if length ($question) < 4;

	# I also interpret anything other than [a-z] as a non-letter
	# which should therefore not appear in a question
	unless ($question =~ /^[a-z]{4}$/) {
	    # find the last non-letter in the question
	    1 while ($question =~ /([^a-z])/g);
	    my $non_letter = $1;

	    # find the last non-letter's position in the question
	    my $pos = rindex ($question, $non_letter);

	    # adjust $i to one place past the offending character...
	    $i += $pos + 1;

	    # ...  and try again
	    redo;
	}

	if (exists $answers{$question}) {
	    # if we've seen this question before it can't be unique
	    undef $answers{$question};
	}

	else {
	    # otherwise we need to note the answer
	    $answers{$question} = $word;
	}
    }
}

open (QUESTIONS, '>questions') || die "couldn't open questions: $!\n";
open (ANSWERS, '>answers')     || die "couldn't open answers: $!\n";

foreach my $question (sort keys %answers) {
    next unless defined $answers{$question};
    print QUESTIONS "$question\n";
    print ANSWERS    "$answers{$question}\n";
}

# pedantic, yes, but I don't know how full your disk is
close ANSWERS   || die "couldn't close answers: $!\n";
close QUESTIONS || die "couldn't close questions: $!\n";

