in reply to Recursion problem
In essence this problem requires that you generate the subsets of the original set. Say you have the set (1,2,3,4). You want to find all these subsets
One neat way to get all the combinations is to use a binary approach where the presence of absence of a binary 1 is used to represent "grab this element" from the set. The number of possible combinations is (2**n)-1. It is easier to see in code:1 1 2 1 3 1 4 1 2 3 1 2 4 1 3 4 1 2 3 4 2 2 3 2 4 2 3 4 3 3 4 4
my @list = (1,2,3,4); my $n = 2**@list -1; for $b(1..$n) { printf "%2d: %04b ", $b, $b; my $i = $b; for (@list) { print "$_ " if $i%2; $i >>= 1; } print "\n"; } __DATA__ 1: 0001 1 (get element 0) 2: 0010 2 (get element 1) 3: 0011 1 2 (get elements 0 and 1) 4: 0100 3 (get element 2) 5: 0101 1 3 (etc) 6: 0110 2 3 7: 0111 1 2 3 8: 1000 4 9: 1001 1 4 10: 1010 2 4 11: 1011 1 2 4 12: 1100 3 4 13: 1101 1 3 4 14: 1110 2 3 4 15: 1111 1 2 3 4
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Recursion problem
by psini (Deacon) on May 25, 2008 at 14:53 UTC | |
by Limbic~Region (Chancellor) on May 26, 2008 at 18:45 UTC | |
by psini (Deacon) on May 26, 2008 at 21:37 UTC | |
by Limbic~Region (Chancellor) on May 26, 2008 at 22:39 UTC |