I have an array reference like below:
my $strings = [qw(a b c d)];
I want to form all possible combination and create an array of array as:
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]))]
What I tried:
foreach my $n(1..scalar(@array)) {
my $iter = combinations($strings, $n);
while (my $c = $iter->next) {
print "@$c\n";
}
}
We use the size() method to get the number of elements in the list. We set a constant value 2 to r, i.e., the number of items being chosen at a time. After that, we use the combination formula, i.e., fact(n) / (fact(r) * fact(n-r)) and store the result into the result variable.
Using Algorithm::Combinatorics to find all combinations.
#!/#!/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;
Output:
$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'
]
];
If you don't have the module at hand, and you don't care about the outer level order:
sub fu {
my ($base,@rest) = @_;
my @result = @$base && $base || ();
push @result, fu( [@$base, shift @rest], @rest) while @rest;
return @result;
}
my @output = fu([],qw(a b c d));
Contents of @output
:
[["a"],["a","b"],["a","b","c"],["a","b","c","d"],["a","b","d"],["a","c"],["a","c","d"],["a","d"],["b"],["b","c"],["b","c","d"],["b","d"],["c"],["c","d"],["d"]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With