4
$\begingroup$

I have a function which takes a list as an argument, and I have to swap two precise elements of the list. My call is of the form

f[h1_,{n1___}] := 

I need that under a certain test which will be an a If statement, two precise elements of n1 are switched. I may therefore need a Module to store the intermediate list and call my function f with the new list. I checked Swapping elements of list and Swap elements in list without copy but in both those questions, the proposed function never return the desired list but just modify the actual list.

f[h1_,{n1___}] = If[test=True,f[h1,{swappedN1}],ElseStatement]

I therefore need a function that makes

swap[{1,2,3,4},1,2] -> {2,1,3,4}

such that I can do something like

 f[h1_,{n1___}] = If[test=True,f[h1,swap[{n1},pos1,pos2],ElseStatement]

Is that possible in Mathematica ?

$\endgroup$

2 Answers 2

5
$\begingroup$

Just use a temporary variable:

swap[a_List, p_, q_] := Module[{aa = a}, aa[[{p, q}]] = aa[[{q, p}]]; aa]

swap[{1, 2, 3, 4}, 1, 2]
{2, 1, 3, 4}

Actually I just remembered there is a built-in for this: Permute with Cycles

Permute[{1, 2, 3, 4}, Cycles[{{1, 2}}]]
{2, 1, 3, 4}

Also ReplacePart is rather clean:

swap[a_, p_Integer, q_Integer] := ReplacePart[a, {p -> a[[q]], q -> a[[p]]}]
$\endgroup$
1
  • $\begingroup$ Nice, thank you very much ! $\endgroup$
    – Ezareth
    Commented Mar 12, 2017 at 14:04
3
$\begingroup$
list = Range[4];

SubsetMap[RotateRight, list, {1, 2}]

{2, 1, 3, 4}

SubsetMap[RotateRight, list, {2, 4}]

{1, 4, 3, 2}

swap[a_, b_, c_] := SubsetMap[RotateRight, a, {b, c}]

swap[list, 1, 2]

{2, 1, 3, 4}

Addendum (not part of the question, but good to know)

We can also employ swap to change matrix rows or columns:

list = ArrayReshape[Range[12], {3, 4}];

list // MatrixForm

enter image description here

Swap rows 1 and 2

swap[list, 1, 2] // MatrixForm

enter image description here

Swap columns 2 and 3

Query[All, swap[#, 2, 3] &] @ list 

or, alternatively,

ArrayReduce[swap[#, 2, 3] &, list, 2]

give

enter image description here

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.