由于 X
阵列的数量,每一个可能不同数量的元素,我该怎么过,我从每个阵列一个项目的所有组合循环?
Given x
number of arrays, each with a possibly different number of elements, how can I iterate through all combinations where I select one item from each array?
例如:
[ ] [ ] [ ]
foo cat 1
bar dog 2
baz 3
4
返回
[foo] [cat] [ 1 ]
[foo] [cat] [ 2 ]
...
[baz] [dog] [ 4 ]
我这样做在Perl,顺便说一句。
I'm doing this in Perl, btw.
递归和更流畅的Perl的例子(带解说和文档)做的笛卡尔乘积可以在 http://www.perlmonks.org/?node_id=7366
Recursive and more-fluent Perl examples (with commentary and documentation) for doing the Cartesian product can be found at http://www.perlmonks.org/?node_id=7366
例如:
sub cartesian {
my @C = map { [ $_ ] } @{ shift @_ };
foreach (@_) {
my @A = @$_;
@C = map { my $n = $_; map { [ $n, @$_ ] } @C } @A;
}
return @C;
}
上一篇:在无向图检查奇数周期奇数、周期
下一篇:合并树节点节点