Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re: Generating all possible combinations from an AoA

by Anonymous Monk
on Apr 13, 2011 at 20:34 UTC ( [id://899294]=note: print w/replies, xml ) Need Help??


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! :-)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://899294]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (8)
As of 2024-04-18 08:12 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found