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

前端 未结 5 775
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:32

    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

    Example:

    sub cartesian {
        my @C = map { [ $_ ] } @{ shift @_ };
    
        foreach (@_) {
            my @A = @$_;
    
            @C = map { my $n = $_; map { [ $n, @$_ ] } @C } @A;
        }
    
        return @C;
    }
    

提交回复
热议问题