在Perl中,我怎么可以遍历多套笛卡尔积?笛卡尔、遍历、多套、我怎么

2023-09-11 02:28:29 作者:?●烟祭ヽ

由于 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;
}
 
精彩推荐
图片推荐