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

前端 未结 5 772
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条回答
  •  一向
    一向 (楼主)
    2020-12-21 02:44

    You can use nested loops.

    for my $e1 (qw( foo bar baz )) {
    for my $e2 (qw( cat dog )) {
    for my $e3 (qw( 1 2 3 4 )) {
       my @choice = ($e1, $e2, $e3); 
       ...
    }}}
    

    When you need an arbitrary number of nested loops, you can use Algorithm::Loops's NestedLoops.

    use Algorithm::Loops qw( NestedLoops );
    
    my @lists = (
       [qw( foo bar baz )],
       [qw( cat dog )],
       [qw( 1 2 3 4 )],
    );
    
    my $iter = NestedLoops(\@lists);
    while ( my @choice = $iter->() ) {
       ...
    }
    

提交回复
热议问题