2013-09-30 44 views
2

我有數組數組。獲取N個陣列的所有組合

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

,並希望有這樣的結果:

@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'], 
) 

我輸入數組@a有2至6嵌套數組

不知道如何找到CPAN此功能。

+1

使用http://search.cpan.org/perldoc?Math%3A%3ACombinatorics – Jean

+0

是的,我看到了。但它沒有組合,沒有排列,也沒有錯誤。這一切都源於這一點。 –

+0

還有[Set :: CrossProduct](http://search.cpan.org/~bdfoy/Set-CrossProduct-1.95/lib/Set/CrossProduct.pm) –

回答

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

是的,謝謝! –

1

爲什麼選擇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); 
+0

它並不總是3維。我有@a作爲輸入,並且它有2到6個數組。 –

+5

這就是爲什麼cpan – mob