Korjavin Ivan
Korjavin Ivan

Reputation: 449

Get all combinations from N arrays

I have array of arrays.

@a=([1,2,3],['b','r','g'],['L','X']);

And want to have this result:

@b=(
[1,'b','L'],[1,'b','X'],
[1,'r','L'],[1,'r','X'],
[1,'g','L'],[1,'g','X'],

[2,'b','L'],[2,'b','X'],
[2,'r','L'],[2,'r','X'],
[2,'g','L'],[2,'g','X'],

[3,'b','L'],[3,'b','X'],
[3,'r','L'],[3,'r','X'],
[3,'g','L'],[3,'g','X'],
)

My input array @a have from 2 to 6 nested arrays

Dont know how to find this function on cpan.

Upvotes: 2

Views: 1060

Answers (2)

ikegami
ikegami

Reputation: 385655

use Algorithm::Loops qw( NestedLoops );
my @b; NestedLoops(\@a, sub { push @b, [ @_ ] });

Upvotes: 5

CowboyTim
CowboyTim

Reputation: 57

Why cpan?

use strict; use warnings;
use Data::Dumper;
my @a=([1,2,3],['b','r','g'],['L','X']);

my @b;
foreach my $i (@{$a[0]}){
    foreach my $c (@{$a[1]}){
        foreach my $k (@{$a[2]}){
            push @b, [$i, $c, $k];
        }
    }
}

print Dumper(\@b);

Upvotes: 1

Related Questions