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$ 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$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.