SHOW:
|
|
- or go back to the newest paste.
1 | #!/bin/perl | |
2 | # | |
3 | # Enumerate all the partitions of {1, 3, 4, 5, 7, 15, 16, 17, 21, 23, 25, 31} | |
4 | # into 4 subsets. | |
5 | # | |
6 | # Samuel DEVULDER, fev 2014 | |
7 | # | |
8 | ||
9 | # 1st: the set | |
10 | $set = 0; | |
11 | for my $x (1, 3, 4, 5, 7, 15, 16, 17, 21, 23, 25, 31) {$set |= 1<<$x;} | |
12 | ||
13 | - | for $part (&all_k_partition(4, $set, 0)) { |
13 | + | # 2nd: the number of partitions |
14 | $num = 4; | |
15 | ||
16 | # 3rd: enumerate all | |
17 | $n = 0; | |
18 | for $part (&all_k_partition($num, $set, 0)) { | |
19 | print ++$n, " "; | |
20 | for my $subset (split(',', $part)) {&print_set($subset);} | |
21 | print "\n"; | |
22 | } | |
23 | ||
24 | sub print_set { | |
25 | my($set) = @_; | |
26 | ||
27 | print "{"; | |
28 | my($first) = 1; | |
29 | for(my $i=0; (1<<$i)<=$set; ++$i) { | |
30 | if($set & (1<<$i)) { | |
31 | print "," unless $first; $first = 0; | |
32 | print $i; | |
33 | } | |
34 | } | |
35 | print "} "; | |
36 | } | |
37 | ||
38 | sub next_in_set { | |
39 | my($x, $set) = @_; | |
40 | return ($x-$set) & $set; | |
41 | } | |
42 | ||
43 | sub all_k_partition { | |
44 | my($k, $set, $i) = @_; | |
45 | return () if $set==0 || $k==0 || $set<=$i; | |
46 | return ($set) if $k==1; | |
47 | ||
48 | my(@r); | |
49 | while($i = &next_in_set($i, $set)) { | |
50 | my($m) = $i; | |
51 | for (my $j = 1;$m>>$j;$j<<=1) {$m|=$m>>$j;} | |
52 | for my $j (&all_k_partition($k-1, $set^$i, $m)) { | |
53 | push(@r, "$i,$j"); | |
54 | } | |
55 | } | |
56 | ||
57 | return @r; | |
58 | } |