从数组中的元素创建组合

que*_*nar 7 arrays perl perl-module perl-data-structures

我有一个如下所示的数组引用:

my $strings = [qw(a b c d)];
Run Code Online (Sandbox Code Playgroud)

我想形成所有可能的组合并创建一个数组数组:

my $output = [qw(qw([a],[b],[c],[d],[a,b],[a,c],[a,d],[b,c],[b,d],[c,d],   [a,b,c],[a,b,d],[b,c,d],[a,b,c,d]))]
Run Code Online (Sandbox Code Playgroud)

我尝试了什么:

foreach my $n(1..scalar(@array)) {
    my $iter = combinations($strings, $n);
    while (my $c = $iter->next) {
        print "@$c\n";
    }
}
Run Code Online (Sandbox Code Playgroud)

Cha*_*hak 2

使用Algorithm::Combinatorics查找所有组合。

#!/#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
use Algorithm::Combinatorics qw(combinations);
my @data = qw(a b c d);
my $all_combinations;
foreach (1..4){
    push @$all_combinations, combinations(\@data, $_);
}
print Dumper $all_combinations;
Run Code Online (Sandbox Code Playgroud)

输出:

$VAR1 = [
          [
            'a'
          ],
          [
            'b'
          ],
          [
            'c'
          ],
          [
            'd'
          ],
          [
            'a',
            'b'
          ],
          [
            'a',
            'c'
          ],
          [
            'a',
            'd'
          ],
          [
            'b',
            'c'
          ],
          [
            'b',
            'd'
          ],
          [
            'c',
            'd'
          ],
          [
            'a',
            'b',
            'c'
          ],
          [
            'a',
            'b',
            'd'
          ],
          [
            'a',
            'c',
            'd'
          ],
          [
            'b',
            'c',
            'd'
          ],
          [
            'a',
            'b',
            'c',
            'd'
          ]
        ];
Run Code Online (Sandbox Code Playgroud)