use strict; use warnings; use constant LEFT => -1; use constant RIGHT => 1; print "Enter N: "; chomp( my $n = <> ); my (@dir, @p); for (1 .. $n) { $dir[$_ - 1] = LEFT; $p[$_ - 1] = $_; } my $count = 0; while (1) { printf "%03d: ", ++$count; print "$p[$_ - 1] " for 1 .. $n; print $/; # 1) Find the largest element that has a smaller element in the di +rection # of its arrow, aka the largest "mobile" element. my ($i, $val) = find_max_mobile(\@p, \@dir); # This means we couldn't find an element that's "mobile". That mea +ns we've # run out of permutations. last if $i == -1; # 2) Swap it and the element it's pointing to. We also have to swa +p the # arrows to keep everything in sync. my @indices = ($i, $i + $dir[$i]); @p[ @indices ] = @p[ reverse @indices ]; @dir[ @indices ] = @dir[ reverse @indices ]; # 3) Reverse the direction of all arrows for elements bigger than +the # currently largest "mobile" element. for (0 .. $#p) { $dir[$_] = -$dir[$_] if $p[$_] > $val; } } sub find_max_mobile { my ($p, $dir) = @_; my ($i, $n) = (-1,0); # The first element is the max only if its arrow is pointing RIGHT ($i, $n) = (0, $p->[0]) if $dir->[ 0 ] == RIGHT && $p->[0] > $p->[1]; # A middle element is the max only if its arrow points to a smalle +r value for ( 1 .. $#$p-1 ) { if ( $p->[$_] > $p->[$_ + $dir->[$_]] ) { ($i, $n) = ($_, $p->[$_]) if $n < $p->[$_]; } } # The last element is the max only if its arrow is pointing LEFT if ( $dir->[ $#$p ] == LEFT && $p->[$#$p] > $p->[$#$p - 1] ) { ($i, $n) = ($#$p, $p->[-1]) if $n < $p->[$#$p]; } return ($i, $n); }
Being right, does not endow the right to be rude; politeness costs nothing.
Being unknowing, is not the same as being stupid.
Expressing a contrary opinion, whether to the individual or the group, is more often a sign of deeper thought than of cantankerous belligerence.
Do not mistake your goals as the only goals; your opinion as the only opinion; your confidence as correctness. Saying you know better is not the same as explaining you know better.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Steinhaus - Johnson - Trotter Algorithm for Permutations (explain)
by tye (Sage) on Dec 28, 2004 at 17:44 UTC | |
by barrachois (Pilgrim) on Jan 04, 2005 at 18:55 UTC |