In Perl, how can I iterate over the Cartesian product of multiple sets?

前端 未结 5 788
Happy的楠姐
Happy的楠姐 2020-12-21 02:21

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?

5条回答
  •  猫巷女王i
    2020-12-21 02:48

    My Set::CrossProduct module does exactly what you want. Note that you aren't really looking for permutations, which is the ordering of the elements in a set. You're looking for the cross product, which is the combinations of elements from different sets.

    My module gives you an iterator, so you don't create it all in memory. You create a new tuple only when you need it.

    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->@*;
        }
    

提交回复
热议问题