Ah, a twist. The common question is about permutations.
Nevertheless, I'd still use recursion. Say you need $n elements. Is the first element included? If yes, combine it with all combinations of $n-1 elements from the list of all of the following elements. If no, get all combinations of $n elements of the same sublist. Of course, you need to include every possible solution, which means walking every possible path.
Code!
sub combinations { my $n = shift; return [@_] if $n == @_; return () if $n > @_ or $n < 0; my $first = shift; my @r = ((map [ $first, @$_ ], combinations($n-1, @_)), combinations($n, @_)); return @r; } use Data::Dumper; print Dumper [ combinations(2, (0, 1, 2, 3)) ];
It appears to be working well.
Update: I'm pretty sure inserting
at the appropriate place, i.e. among the other return statements near the top, will improve efficiency quite a bit. It avoids doing a lot of useless recursion if all you want is the empty list as a singleton.return [] if $n == 0;
In reply to Re: Combinatorics
by bart
in thread Combinatorics
by ezekiel
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |