给定x个数组,每个数组可能有不同数量的元素,如何迭代所有组合,我从每个数组中选择一个项目?
例:
[ ] [ ] [ ] foo cat 1 bar dog 2 baz 3 4
返回
[foo] [cat] [ 1 ] [foo] [cat] [ 2 ] ... [baz] [dog] [ 4 ]
我在Perl中这样做,顺便说一下.
解决方法
我的
Set::CrossProduct模块完全符合您的要求.请注意,您并不是在寻找排列,这是排列中元素的排序.您正在寻找交叉产品,它是来自不同集合的元素的组合.
我的模块为您提供了一个迭代器,因此您不会在内存中创建它.只有在需要时才创建新元组.
use Set::Crossproduct; my $iterator = Set::CrossProduct->new( [ [qw( foo bar baz )],[qw( cat dog )],[qw( 1 2 3 4 )],] ); while( my $tuple = $iterator->get ) { say join ' ',$tuple->@*; }