Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create combinations from elements in an array

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";
    }
}
like image 589
questionar Avatar asked Sep 22 '16 07:09

questionar


People also ask

How do you generate all possible combinations of a set of numbers in Java?

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.


2 Answers

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'
          ]
        ];

like image 151
Chankey Pathak Avatar answered Sep 17 '22 11:09

Chankey Pathak


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"]]
like image 44
Richard RP Avatar answered Sep 18 '22 11:09

Richard RP