in reply to Generating all possible combinations from an AoA

Using foreach loops only:
my @results = (""); foreach my $subarray (@array) { my @tmp_results = (); my @subarray = @{ $subarray }; foreach my $tmp_result (@results) { foreach my $element (@subarray) { my $string = $tmp_result . $element; push @tmp_results, $string; } } @results = @tmp_results; } print join "\n", @results; print "\n";

The trick is in the overwritting of @results with @tmp_results at the end of the outer loop, as well as in initializing @results with a single empty list in order for concatenation to work further down.

This could probably be written with several map's, but it might become difficult to read.

Replies are listed 'Best First'.
Re^2: Generating all possible combinations from an AoA
by choroba (Cardinal) on Apr 14, 2011 at 12:37 UTC
    Like this?
    @results = (''); foreach my $subarray (@array) { @results = map {my $res = $_; map $res.$_, @$subarray } @results; } print join "\n", @results,'';
      Best answer to this problem I've seen so far, where everybody replies with long solutions or black boxes. Short, no globs, no modules, clear and readable. Very good! :-)