Skip to main content
added 185 characters in body
Source Link
Mr.Wizard
  • 275.2k
  • 34
  • 606
  • 1.5k

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]]}] 

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} 

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]]}] 
Source Link
Mr.Wizard
  • 275.2k
  • 34
  • 606
  • 1.5k

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}