Geez. This isn't supposed to be obfuscation, but it ended up that way, in the sense that the algorithm is a bit difficult to extract. The swapping is the easy part... those two parallel arrays are
not.
# reorder an array using only swap(ARRAY, X, Y),
# given a new set of indices
my @array = qw( put these in a different order );
my @order = qw( 1 3 5 4 2 0 );
reorder_swap(\@array, \@order);
# expected outcome:
# qw( these a order different in put )
sub reorder_swap {
my ($a, $o) = @_;
my @P = my @R = 0 .. $#$o;
for (0 .. $#$o) {
next if $P[$$o[$_]] == $_;
swap($a, $P[$$o[$_]], $_);
(@P[$R[$_],$$o[$_]], @R[$P[$$o[$_]],$_]) =
(@P[$$o[$_],$R[$_]], @R[$_,$P[$$o[$_]]]);
}
}
sub swap {
my ($a, $x, $y) = @_;
@$a[$x,$y] = @$a[$y,$x];
}
For simplicity's sake, here's the for loop with a temporary variable instead:
for (0 .. $#$o) {
my $idx = $$o[$_];
next if $P[$idx] == $_;
swap($a, $P[$idx], $_);
(@P[$R[$_],$idx], @R[$P[$idx],$_]) =
(@P[$idx,$R[$_]], @R[$_,$P[$idx]]);
}
_____________________________________________________
Jeff
japhy Pinyan,
P.L., P.M., P.O.D, X.S.:
Perl,
regex,
and
perl
hacker
How can we ever be the sold short or the cheated, we who for every service have long ago been overpaid? ~~ Meister Eckhart