Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Getting permutations of length n of an array of length greater than n?

by LittleJack (Beadle)
on Jan 18, 2022 at 22:04 UTC ( #11140589=perlquestion: print w/replies, xml ) Need Help??

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

I'm looking at Algorithm::Permute and it doesn't seem to have this feature: given an array of say 8 items, how can I list all permutations of length 5, not the full 8?

  • Comment on Getting permutations of length n of an array of length greater than n?

Replies are listed 'Best First'.
Re: Getting permutations of length n of an array of length greater than n?
by pryrt (Monsignor) on Jan 18, 2022 at 22:15 UTC
    As shown in the Algorithm::Permute synopsis, if you want r elements out of the n objects in each permutation,
    # but also you can create r of n objects permutation generator, where +r <= n my $p = Algorithm::Permute->new([1..4], 3);

    A practical example is shown here, where there are n=4 objects and I take groups of r=2:

    C:\usr\local\share>perl -MAlgorithm::Permute -e "my $p=Algorithm::Perm +ute::->new([1..4],2); while(my @res=$p->next){print qq(@res\n)}" 2 1 1 2 3 2 2 3 3 1 1 3 4 2 2 4 4 3 3 4 4 1 1 4

    Your example would be ...->new([1..8],5) to get permutations of length 5 from the 8 objects given. Or

    C:\usr\local\share>perl -MAlgorithm::Permute -e "my $p=Algorithm::Perm +ute::->new([1..8],5); while(my @res=$p->next){print qq(@res\n)}" 5 4 3 2 1 4 5 3 2 1 4 3 5 2 1 4 3 2 5 1 4 3 2 1 5 5 3 4 2 1 3 5 4 2 1 3 4 5 2 1 3 4 2 5 1 3 4 2 1 5 ... 8 1 2 3 4 1 8 2 3 4 1 2 8 3 4 1 2 3 8 4 1 2 3 4 8

      Thanks! I've got it working now.

      What I failed at was comprehending the CPAN documentation, but you have to admit "you can create r of n objects permutation generator, where r <= n" is a little obscurely worded!

Re: Getting permutations of length n of an array of length greater than n?
by choroba (Archbishop) on Jan 18, 2022 at 22:08 UTC
Re: Getting permutations of length n of an array of length greater than n?
by tybalt89 (Prior) on Jan 18, 2022 at 22:42 UTC

    Alternate way

    #!/usr/bin/perl use strict; # https://perlmonks.org/?node_id=11140589 use warnings; use ntheory qw( forcomb forperm ); forcomb { my @sel = @_; forperm { print @sel[@_], ' ' } scalar @sel; } 8, 5; print "\n";

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (1)
As of 2022-05-22 15:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Do you prefer to work remotely?



    Results (80 votes). Check out past polls.

    Notices?