Terse Method to Swap Lowest for Highest?
How about:
Module[{tmp = test},
With[{ord=Ordering[tmp]},
tmp[[ord]] = Reverse @ tmp[[ord]]];
tmp
]
{56, 9, 4, 3, -5, -2, -3, 1, 2, 7, 60, 58, 8, -4, 10, 6, 59, 5, 57, -1}
This is equivalent to Carl's procedure, except that it uses one less scratch list:
With[{ord = Ordering[test]},
test[[PermutationProduct[Reverse[ord], InversePermutation[ord]]]]]
{56, 9, 4, 3, -5, -2, -3, 1, 2, 7, 60, 58, 8, -4, 10, 6, 59, 5, 57, -1}
Recall that list[[perm]] = list
is equivalent to list = list[[InversePermutation[perm]]]
, where perm
is a permutation list. (The situation is equivalent to list.pmat
being the same as Transpose[pmat].list
if pmat
is a permutation matrix.) You can then use PermutationProduct[]
to compose successive permutations.
(This was supposed to be a comment, but it got too long.)
Permute[Sort @ #, Reverse @ Ordering @ #] & @ test
{56, 9, 4, 3, -5, -2, -3, 1, 2, 7, 60, 58, 8, -4, 10, 6, 59, 5, 57, -1}
Also
Permute[test[[#]], Reverse @ #] & @ Ordering[test]
{56, 9, 4, 3, -5, -2, -3, 1, 2, 7, 60, 58, 8, -4, 10, 6, 59, 5, 57, -1}
and
test[[Reverse @ #]][[Ordering @ #]] & @ Ordering[test]
{56, 9, 4, 3, -5, -2, -3, 1, 2, 7, 60, 58, 8, -4, 10, 6, 59, 5, 57, -1}