in reply to Combinatorics

I don't know about the module, but its a fairly simple (recursive) subroutine:
use Data::Dumper; my @a = (1..4); my $len = 4; print Dumper(combinations($len, @a)); sub combinations { my ($size, @elements) = @_; return [] if $size < 1; my @result = (); foreach my $elem (@elements) { push @result, map { [$elem, @$_] } combinations($size-1, grep { $_ != $elem } @elements) } return @result; }
--Dave

Update: for greater generality, replace foreach loop with

my @seen = (); while (@elements) { my $elem = shift @elements; push @result, map { [$elem, @$_] } combinations($size-1, @seen, @elements); push @seen, $elem; }

Replies are listed 'Best First'.
Re: Re: Combinatorics
by ezekiel (Friar) on Aug 22, 2002 at 03:01 UTC

    This looks great! except that it gives permutations rather than combinations. For example, it produces both (1, 2, 3) and (1, 3, 2) whereas, for my purposes, these are the same thing i.e., order is not important. It gives me a starting point though - thanks!