Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re: Combinatorics

by dpuu (Chaplain)
on Aug 22, 2002 at 02:43 UTC ( [id://191908]=note: print w/replies, xml ) Need Help??


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 (Pilgrim) 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!

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://191908]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (4)
As of 2024-04-16 06:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found