5. Example IIb: statistics

How to make combinations of a set of numbers?
This code uses the Math::Combinatorics module (https://metacpan.org/pod/Math::Combinatorics) to generate combinations of size $k from the array @set.


use Math::Combinatorics; 

@set = (1, 2, 3, 4);
$k = 2;

$combinat = Math::Combinatorics->new(data => [@set], count => $k);

while (@combo = $combinat->next_combination) {
    print "@combo\n";
}
Output:

1 2
1 3
1 4
2 3
2 4
3 4
How to make permutations of a set of numbers?
To generate permutations in Perl, you can use the Algorithm::Permute module from CPAN: https://metacpan.org/pod/Algorithm::Permute

use Algorithm::Permute; 

my @items = (1, 2, 3);
my $permutor = Algorithm::Permute-> new(\@items);

while (@perm = $permutor-> next) {
    print join(", ", @perm), "\n";
}
Output:

3, 2, 1
2, 3, 1
2, 1, 3
3, 1, 2
1, 3, 2
1, 2, 3
You can alo create r of n objects permutation generator, where r <= n

use Algorithm::Permute; 

$permutor = Algorithm::Permute->new([1..4], 3);

while (@perm = $permutor-> next) {
    print join(", ", @perm), " | ";
}
Output:

3, 2, 1 | 2, 3, 1 | 2, 1, 3 | 3, 1, 2 | 1, 3, 2 | 1, 2, 3 | 
4, 3, 2 | 3, 4, 2 | 3, 2, 4 | 4, 2, 3 | 2, 4, 3 | 2, 3, 4 | 
4, 3, 1 | 3, 4, 1 | 3, 1, 4 | 4, 1, 3 | 1, 4, 3 | 1, 3, 4 | 
4, 2, 1 | 2, 4, 1 | 2, 1, 4 | 4, 1, 2 | 1, 4, 2 | 1, 2, 4 |