# The fastest Perl permutation algorithm I've yet found. It's only 20-30% slower
# than Algorithm::PermuteInPlace.
#
# Now if we implement _this_ in C, with a Perl callback for processing
# the permutation, we can probably get even faster than Algorithm::PermuteInPlace.
# (There are ways to invoke Perl callbacks without the normal subcall overhead.)
# Translated from the C code by Matt Day,
# at http://www.cs.jyu.fi/user/hirvonen/opk_2001_ratk/permu.txt
use strict;
sub permute {
my ($aref, $level) = (@_, 0);
my ($index, $copy, $printing) = ($level, [@$aref], $level+1 == @$aref);
do {
if ($printing) {
print "@$copy\n";
} else {
permute($copy, 1+$level);
}
@$copy[$index-1, $index] = @$copy[$index, $index-1]
if $index != 0;
} while $index-- > 0;
}
permute([1..shift]);