Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Combinations of array?

by dagwood00 (Initiate)
on Jun 09, 2012 at 01:04 UTC ( #975263=perlquestion: print w/replies, xml ) Need Help??

dagwood00 has asked for the wisdom of the Perl Monks concerning the following question:

Hi Everyone - need some wisdom!!! I'm trying to work out creating a set of combinations for something as follows: @array = qw( A B C D E); I need to generate something like the follow set of combinations:
A			
A	B		
A		C	
A			D	
A	B	C	
A	B	C	D
        B
        B       C
        B       C       D
                C
                C       D
                        D
I may have missed some combinations, but I think this is the general pattern. I need to generate every pattern possible. I've looked at Algorithm::Permute and Algorithm::Loops, but these provide permutations and this is not really permutations. Any help, leads or examples would be definitely appreciated.

Replies are listed 'Best First'.
Re: Combinations of array?
by toolic (Bishop) on Jun 09, 2012 at 01:16 UTC
    Algorithm::Combinatorics
    use warnings; use strict; use Data::Dumper; use Algorithm::Combinatorics qw(combinations); my @array = qw(A B C D); for (1 .. 4) { my @combos = combinations(\@array, $_); print Dumper(\@combos); } __END__ $VAR1 = [ [ 'A' ], [ 'B' ], [ 'C' ], [ 'D' ] ]; $VAR1 = [ [ 'A', 'B' ], [ 'A', 'C' ], [ 'A', 'D' ], [ 'B', 'C' ], [ 'B', 'D' ], [ 'C', 'D' ] ]; $VAR1 = [ [ 'A', 'B', 'C' ], [ 'A', 'B', 'D' ], [ 'A', 'C', 'D' ], [ 'B', 'C', 'D' ] ]; $VAR1 = [ [ 'A', 'B', 'C', 'D' ] ];
      This worked for what I needed. Thanks for you help!
Re: Combinations of array?
by ambrus (Abbot) on Jun 10, 2012 at 09:28 UTC
Re: Combinations of array?
by jaredor (Priest) on Jun 17, 2012 at 06:30 UTC

    Late to the party and, not only that, but wearing the same outfit as some (see ambrus's link above). I think the best answer for you is toolic's. My answer that follows just fills in a few conceptual details for you about the Power Set, illustrated by two functions that do the job two different ways.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://975263]
Approved by ww
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (6)
As of 2020-07-06 06:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?