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
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.