Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much

RE: Permutations and combinations

by AltBlue (Chaplain)
on Aug 21, 2000 at 13:19 UTC ( #28783=note: print w/ replies, xml ) Need Help??

in reply to Permutations and combinations

interesting approach that reminded me about some old project that needed some permutations generations stuff... so, i've checked up that code and here i come with a reviewed standalone version:

#!/usr/bin/perl -w # DESCRIPTION: Generate permutations in lexicographic order # USAGE: ./ <term1> <term2> <term3> ..... use strict; die "bleah... nothing to permutate\n" if $#ARGV<0; my @terms = @ARGV; my $n = $#ARGV; my @a = (0..$n); genperm(); exit(0); sub genperm { print join(" ",@terms[@a]),"\n"; my ($k,$j) = ($n-1,$n); $k-- while ($k>=0 and $a[$k]>$a[$k+1]); return(0) if ($k<0); $j-- while ($a[$k]>$a[$j]); swap($j,$k++); $j=$n; swap($j--,$k++) while ($j>$k); genperm(); } sub swap { my ($i,$j) = @_; my $t = $a[$i]; ($a[$i],$a[$j]) = ($a[$j],$t); }

as you may see, it's a pure lexicographic permutations generator algorithm, as in the books ;-)

oh, not to forget, just checked up on cpan and found out there is a Algorithm::Permute module. here is a lame example for module users ;-)

#!/usr/bin/perl -w use strict; die "bleah... nothing to permutate\n" unless defined @ARGV; use Algorithm::Permute qw(permute permute_ref); print join(" ", @$_), "\n" for permute(\@ARGV);


Comment on RE: Permutations and combinations
Select or Download Code
Replies are listed 'Best First'.
Re: RE: Permutations and combinations
by I0 (Priest) on Apr 19, 2002 at 04:17 UTC
    your sub swap can be written without $t:
    sub swap { my ($i,$j) = @_; @a[$i,$j] = @a[$j,$i]; }
      lol, you bother to look upon this old piece of code :))

      heh, of course that your snippet is good, but a swap routine could be written even simpler:

      sub swap { reverse @_ }
      ... heh, it's not the case for that code thou, as the array is a global one :) cheers.


Log In?

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

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (5)
As of 2015-11-27 07:54 GMT
Find Nodes?
    Voting Booth?

    What would be the most significant thing to happen if a rope (or wire) tied the Earth and the Moon together?

    Results (720 votes), past polls