-
Notifications
You must be signed in to change notification settings - Fork 0
/
combinations
executable file
·63 lines (54 loc) · 974 Bytes
/
combinations
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#!/usr/bin/perl
use warnings;
use strict;
$|=1;
#my @populations = ("A", "B", "C", "D", "E", "F");
my $N = 126;
my $R = 3;
my @populations;
for (1 .. $N)
{
push(@populations, $_);
}
my @sets = combinations($N, $R, @populations);
my $expectedNo = ncr($N, $R);
print "sets: " . @sets . " combinations (expected is $expectedNo)\n" . join("\n", @sets) . "\n";
sub ncr
{
my $n = shift;
my $r = shift;
if($r==1)
{
return $n;
}
elsif ($n==$r)
{
return 1;
}
else
{
return ncr($n-1, $r) + ncr($n-1,$r-1);
}
}
sub combinations
{
my $n = shift;
my $r = shift;
my @pop = @_;
#print "n= $n\n";
#print "r= $r\n";
#print "pop = @pop\n";
if($r==1)
{
return @pop;
}
elsif ($n==$r)
{
return (join(",", @pop));
}
else
{
my $firstPop = shift(@pop);
return (combinations($n-1, $r, @pop), map{join(",", $firstPop, $_)} combinations($n-1, $r-1, @pop)) ;
}
}