# takes an integer word length and a list of letters,
# returns a list of words of the integer length
#
{ my %cache;
sub wordz {
my ( $n, @letters ) = @_;
my $cache_key = join( '', @letters, $n );
return if $n > @letters;
return @letters if $n == 1;
return @{ $cache{ $cache_key } } if exists $cache{ $cache_key };
my @wordz;
for ( my $i = 0; $i <= $#letters; $i++ ) {
push @wordz, map { $letters[ $i ] . $_ }
wordz( $n - 1, @letters[ 0 .. $i - 1 ],
@letters[ $i + 1 .. $#letters ] );
my @o = wordz( $n, @letters[ $i + 1 .. $#letters ] );
push @wordz, @o;
}
$cache{ $cache_key } = \@wordz;
return @wordz;
}
}
It is also fun to do this problem non-recursively. If you are interested in that, I also have code (though there are different possible approaches).
-Colin.
WHITEPAGES.COM | INC