Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re: permutations of array

by jynx (Priest)
on Feb 22, 2002 at 05:28 UTC ( [id://146883]=note: print w/replies, xml ) Need Help??


in reply to permutations of array


a couple of things,

The major problem with the code you have there is that it doesn't give combinations of separated list items, it only gives items from one point forward. As an example:
for n=3, with items 1,2, and 3, i get the following from your code:
1
1 2
1 2 3
2
2 3
3
Note the missing '1 3' case. For the items 1,2,3, and 4, '134', '124', '13', '14', etc would be missing.

Merlyn's snippets are a nice and easy way to go; a simple transformation and they will return an array of strings instead of an AoA. As an exercise, i chalked up a non-recursive solution as well; it returns an array of arrays as merlyn's does.

sub combinations { my (@comb, $pos); my $limit = 2**@_; while (my $item = shift) { my $step = 2**@_; for ($pos = 0; $pos < $limit; $pos += $step) { push @{$comb[$pos++]}, $item for 1..$step; } } return @comb, []; }
jynx

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (6)
As of 2024-04-19 11:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found