RosettaCodeData/Task/Combinations/Perl5i/combinations.perl5i

23 lines
614 B
Plaintext

use perl5i::2;
# ----------------------------------------
# generate combinations of length $n consisting of characters
# from the sorted set @set, using each character once in a
# combination, with sorted strings in sorted order.
#
# Returns a list of array references, each containing one combination.
#
func combine($n, @set) {
return unless @set;
return map { [ $_ ] } @set if $n == 1;
my ($head) = shift @set;
my @result = combine( $n-1, @set );
for my $subarray ( @result ) {
$subarray->unshift( $head );
}
return ( @result, combine( $n, @set ) );
}
say @$_ for combine( 3, ('a'..'e') );