Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Permuting n elements

by tilly (Archbishop)
on Aug 24, 2000 at 08:19 UTC ( #29373=snippet: print w/replies, xml ) Need Help??
Description: This is a faster version of How do I permute N elements of a list?. The odds are very good that it spends more time printing than permuting. Put in an if test around the print to print, say, every 100 lines or so to see it really fly.

The reason that it is more efficient than the FAQ is that it spends as little energy copying data as possible.

#!/usr/bin/perl -n
# tsc-permute: permute each word of input
use subs qw( _permute );
permute(split);

{
  my @perm;
  my @unperm;

  sub permute {
    @perm = ();
    @unperm = @_;
    _permute;
  }

  sub _permute {
    if (@unperm) {
      push @perm, pop @unperm;
      foreach (1..@perm) {
        push @perm, shift @perm;
        _permute;
      }
      push @unperm, pop @perm;
    }
    else {
      print "@perm\n";
    }
  }
} 
Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: snippet [id://29373]
help
Chatterbox?
[Corion]: DST does that to everybody...
Corion attempts to find who to address to better target his drive-by patches
[Corion]: This time it's for the Duktape embedded Javascript engine, which would be nice to have IMO, but doesn't compile on Windows currently
[Corion]: I imagine it would be fun to have WWW::Mechanize:: Duktape, but I haven't seen a web browser written in Javascript yet, except the ones distributed with PhantomJs

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (10)
As of 2017-03-27 11:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Should Pluto Get Its Planethood Back?



    Results (319 votes). Check out past polls.