#!/usr/bin/perl
# From "Mathematical Thinking: Problem-Solving and Proofs" SE, pp 22, 1.26
#
# A: I know you have three sons. How old are they?
# B: If you take their ages, expressed in years, and multiply those numbers, the result will equal your age.
# A: But that's not enough to tell me the answer!
# B: The sum of these three numbers equals the number of windows in that building.
# A: Hmm... But it's still not enough!
# B: My middle son is red-haired.
# A: Ah, now it's clear!
#
# How old are the sons?
#
# Solver by Matt Sparks, 20060825
#
my %sets;
my %ages;
for my $x (1..20) {
    for my $y (1..20) {
        for my $z (1..20) {
            $s=join(' ',sort($x,$y,$z));
            $ages{$s}=[$x,$y,$z];
        }
    }
}

for my $k (sort keys %ages) {
    my($x,$y,$z)=@{$ages{$k}};
    $sum = $x+$y+$z;
    $prod = $x*$y*$z;
    next if $prod > 80 || $prod < 30;
    push @{$sets{"$sum $prod"}},[$x,$y,$z];
}

for my $j (keys %sets) {
    my($s,$p)=split / /,$j;
    my @m = @{$sets{$j}}; # array of array refs..
    next if @m < 2;
    for my $r (@m) {
        my($x,$y,$z)=@{$r};
        next if $x==$y or $x==$z or $y==$z;
        print "Solution: $x $y $z (mailman age: $p, windows: $s)\n";
    }
}
