在Perl中,我怎么可以遍历多套笛卡尔积? [英] In Perl, how can I iterate over the Cartesian product of multiple sets?

查看:205
本文介绍了在Perl中,我怎么可以遍历多套笛卡尔积?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于 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;
}

这篇关于在Perl中,我怎么可以遍历多套笛卡尔积?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆