Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine

Re: Generating all possible combinations from an AoA

by LanX (Canon)
on Apr 13, 2011 at 12:42 UTC ( #899174=note: print w/ replies, xml ) Need Help??

in reply to Generating all possible combinations from an AoA



Generate dynamically a string of the above code with all nesting and eval it. (fast and intuitive!)

2. Recursion

Write a function X2() which gets two arrayrefs and returns an arr_ref of the cross product. Call it recursively until @array exceeded.

3. Reduce

is a variation of the above, with List::Util::reduce

use Data::Dumper; #- crossproduct of two array refs sub X2 { my ($a,$b)=@_; my @result; for my $x (@$a) { for my $y (@$b) { unless (ref($x) eq "ARRAY"){ push @result, [$x,$y]; }else{ push @result, [(@$x,$y)]; } } } return \@result; } use List::Util qw/reduce/; #- crossproduct of list of array refs sub X { reduce { X2($a,$b) } @_ } my @array = ( [ "a", "b", "c", ], [ "1", "2", "3", "4", ], [ "x", "y", ], ); print Dumper X(@array);

The function X() now works somehow like the X operator in perl6, but of course you could also use reduce { X2($a,$b) } @array directly.

The function X2() could be rewritten with two nested maps, but thats a little two cryptic for my taste.

Bad ideas:

1. Glob

that's a hack which only works for strings as element type, everything else will be stringified, eg refs!!!

Cheers Rolf


* just noticed that you only want a simple concatenation of strings. That simplifies the code...

* There is a problem with this code .. the first one to spot it gets upvoted! :)

Comment on Re: Generating all possible combinations from an AoA
Select or Download Code

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (6)
As of 2014-07-12 09:21 GMT
Find Nodes?
    Voting Booth?

    When choosing user names for websites, I prefer to use:

    Results (239 votes), past polls