5

I am new to using Mathematica and I can not find a solution to what I am wanting to do.

I want to take a list such as:

x = {1,2,3,4,5,6,7,8}

and a second list (permutation):

perm = {4,1,6,2,7,3,8,5}

and get a result to where the permutation is applied to x. So the return would be 2,4,6,1,8,3,5,7.

My goal is a function like permutationEncrypt[x_, permutation_] := return x with the permutation applied to it

I know I can sort a list, but how would I accomplish what I am wanting to do?

connor
  • 143
  • 5

4 Answers4

6

A simple way is:

y = x; y[[perm]] = x; y
(* {2, 4, 6, 1, 8, 3, 5, 7} *)
Simon Woods
  • 84,945
  • 8
  • 175
  • 324
5

Permute gives what you expect to get from permutationEncrypt:

Permute[x, perm]
(* {2, 4, 6, 1, 8, 3, 5, 7} *)

You can also use Ordering:

peF[x_, p_] := x[[Ordering @ p]]

peF[x, perm]
(* {2, 4, 6, 1, 8, 3, 5, 7} *)

Or, ReplaceAll:

peF2 = # /. Thread[#2 -> #] &;

peF2[x, perm]
(* {2, 4, 6, 1, 8, 3, 5, 7} *)
kglr
  • 394,356
  • 18
  • 477
  • 896
3

Timings for the methods posted:

Needs["GeneralUtilities`"]

f1[{x_, perm_}] := Permute[x, perm]
f2[{x_, perm_}] := x[[Ordering @ perm]]
f3[{x_, perm_}] := Table[x[[Position[perm, i][[1, 1]]]], {i, Length[x]}]
f4[{x_, perm_}] := Module[{y = x}, y[[perm]] = x; y]

BenchmarkPlot[
 {f1, f2, f3, f4},
 {RandomInteger[99, #], RandomSample@Range@#} &,
 TimeConstraint -> 15
]

enter image description here

So it seems Simon's code beats the built-in function. :^)

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
0

Although not as elegant, this also works.

Table[x[[Position[perm, i][[1, 1]]]], {i, Length[x]}]
bbgodfrey
  • 61,439
  • 17
  • 89
  • 156