Swap the two given indices

31

3

Given an array of positive integers and two distinct valid indices, return the array with the two elements corresponding to the two indices swapped.

You may choose to use 0-indexing or 1-indexing, but the testcases below will be 0-indexed.

array        m n output
[1,2,3,4]    0 1 [2,1,3,4]
[5,8,9]      0 2 [9,8,5]
[11,13,15,3] 1 2 [11,15,13,3]
[11,13,15,3] 2 1 [11,15,13,3]
[11,15,15,3] 2 1 [11,15,15,3]

This is . Shortest answer in bytes wins. Standard loopholes apply.

Leaky Nun

Posted 2017-06-22T10:28:30.630

Reputation: 45 011

Related, related. – Leaky Nun – 2017-06-22T10:28:42.087

1Huh, this may well be a task that many golfing languages have a hard time with but most practical languages find easy. (Lists with mutable elements aren't a common thing for golfing languages to have.) If that is the case, it'll be quite interesting. (The golfing languages will probably still win, though, because they're so much terser they can get away with a more complex algorithm.) – None – 2017-06-22T10:36:40.900

7Surprised this probably isn't a dupe, but this challenge is actually creative, since it's a real challenge for many golfing languages out there. – Erik the Outgolfer – 2017-06-22T10:45:44.020

@LeakyNun I've got downvotes (and even delete votes) like that in the past, don't worry too much about it... – Erik the Outgolfer – 2017-06-22T10:46:45.103

Can m and n be taken as an array? – Okx – 2017-06-22T11:23:36.523

Can the output not be in the form of a list (print the integers separated by a newline instead)? – Mr. Xcoder – 2017-06-22T11:27:12.957

Can functions return by modifying the original array in place? – Neil – 2017-06-22T11:34:02.337

@Okx I do not understand what you mean by m and n be taken as an array. – Leaky Nun – 2017-06-22T11:43:48.717

@Neil allowed by meta

– Leaky Nun – 2017-06-22T11:46:37.257

@Mr.Xcoder I'm surprised that I can't find it on meta. – Leaky Nun – 2017-06-22T11:47:35.607

@ais523 I've added one more testcase. – Leaky Nun – 2017-06-22T11:48:20.730

Will the elements of the array be unique as they are in the test cases? – Dennis – 2017-06-22T13:53:41.747

@Dennis nice observation. I've added one more testcase. – Leaky Nun – 2017-06-22T14:26:59.163

Full reentrancy should be a possible bonus! – Cody Gray – 2017-06-23T08:44:04.403

Answers

17

C/C++, 53 50 39 bytes

f(a,m,n)int*a;{a[m]^=a[n]^=a[m]^=a[n];}

Try it online

Saved 11 bytes thanks to @Dennis

Ra8

Posted 2017-06-22T10:28:30.630

Reputation: 391

10

Operation Flashpoint scripting language, 98 95 bytes

f={t=_this;a=t select 0;b=+a;m=t select 1;n=t select 2;a set[m,b select n];a set[n,b select m]}

Modifies the array directly.

Explanation:

t=_this;                   // Give a shorter name for the array of arguments.

a=t select 0;              // Let 'a' be a pointer to the array that we modify.
                           // (The language doesn't have a concept of pointers really,
                           // yet its array variables are pointers to the actual array.)

b=+a;                      // Make a copy of the original array and save a pointer to it
                           // in the variable 'b'. This saves a few bytes later.

m=t select 1;              // Read the index arguments from the input array and save them
n=t select 2;              // to their respective variables.

a set[m,b select n];       // Do the swapping by reading the values from the copy and
a set[n,b select m]        // writing them to the original array. The last semicolon can
                           // be omitted because there are no more statements following 
                           // the last statement.

Call with:

array = [1,2,3,4];
str = format["%1", array];
[array, 0, 1] call f;
hint format["%1\n%2", str, array];

Output:

enter image description here

Steadybox

Posted 2017-06-22T10:28:30.630

Reputation: 15 798

7

JavaScript ES6, 36 32 bytes

Look, Ma, no temporary variable!

(a,m,n)=>[a[m],a[n]]=[a[n],a[m]]

Try it

Enter a comma separated list of elements for a and 2 integers for m & n.

f=
(a,m,n)=>[a[m],a[n]]=[a[n],a[m]]
oninput=_=>o.innerText=(f(b=i.value.split`,`,+j.value,+k.value),b);o.innerText=(f(b=(i.value="5,8,9").split`,`,j.value=0,k.value=2),b)
*{font-family:sans-serif}input{margin:0 5px 0 0;width:100px;}#j,#k{width:50px;}
<label for=i>a: </label><input id=i><label for=j>m: </label><input id=j type=number><label for=k>n: </label><input id=k type=number><pre id=o>

Shaggy

Posted 2017-06-22T10:28:30.630

Reputation: 24 623

2Those instructions modify the array, which means you're allowed to not return the array, which will save you a few bytes. – Neil – 2017-06-22T12:14:43.047

@Neil: You're saying to just use (a,m,n)=>[a[m],a[n]]=[a[n],a[m]]? That would only output the 2 swapped elements without the rest of the array (e.g., [5,8,9],0,2 -> [9,5]). – Shaggy – 2017-06-22T13:33:19.283

@Neil: Right, which is why we need the a at the end to give us the complete, modified array. Or am I completely missing what you're trying to say? – Shaggy – 2017-06-22T14:16:52.010

@Neil: Hmm ... OK, I think I see what you'e getting at now (Sorry, trying to do too many things at the same time today). Thanks for the tip. Is there a consensus on that and, if so, would you have a link handy before I go searching for it myself? – Shaggy – 2017-06-22T14:50:12.000

1https://codegolf.meta.stackexchange.com/a/4942/48934 – Neil – 2017-06-22T14:59:24.767

Surely splicing is shorter? – Downgoat – 2017-06-22T16:52:21.853

@Downgoat, (a,m,n)=>a[m]=a.splice(n,1,a[m])[0] comes in at 35 bytes. – Shaggy – 2017-06-22T16:58:52.440

5

Python 3, 41 32 bytes

-9 bytes thanks to @notjagan

def f(a,m,n):a[m],a[n]=a[n],a[m]

Try it online!

Modifies its argument, which is a valid output format.

ovs

Posted 2017-06-22T10:28:30.630

Reputation: 21 408

3It's funny how it's not even golfed that much comparing to idiomatic python code. – Łukasz Rogalski – 2017-06-22T13:59:16.543

5

MATL, 7 6 bytes

yyP)w(

Indices are 1-based.

Try it online!

Explanation

Consider inputs [11 13 15 3], [2 3].

yy   % Take two inputs implicitly. Duplicate them
     % STACK: [11 13 15 3], [2 3], [11 13 15 3], [2 3]
P    % Flip
     % STACK: [11 13 15 3], [2 3], [11 13 15 3], [3 2]
)    % Reference indexing (pick indexed entries)
     % STACK: [11 13 15 3], [2 3], [15 13]
w    % Swap
     % STACK: [11 13 15 3], [15 13], [2 3]
(    % Assignment indexing (write values into indexed entries). Implicitly display
     % STACK: [11 15 13 3]

Luis Mendo

Posted 2017-06-22T10:28:30.630

Reputation: 87 464

5

Jelly, 7 bytes

Ṛ,ḷyJ}ị

Try it online!

How it works

Ṛ,ḷyJ}ị  Main link. Left argument: [i, j]. Right argument: A (array)

Ṛ        Reverse; yield [j, i].
  ḷ      Left; yield [i, j].
 ,       Pair; yield [[j, i], [i, j]].
    J}   Indices right; yield all indices of A.
   y     Transliterate; replace j with i and i with j.
      ị  Index into A.

Dennis

Posted 2017-06-22T10:28:30.630

Reputation: 196 637

tfw the wrapper is almost as long as the program... – Leaky Nun – 2017-06-22T13:20:13.577

I never knew of the existence of y – Leaky Nun – 2017-06-22T13:23:56.587

I knew of y, but didn't think of using it here. That's a pretty clever answer. – None – 2017-06-22T22:40:47.860

This got me thinking... is Jelly valid Jelly code? – M.Herzkamp – 2017-06-23T14:16:33.823

@M.Herzkamp It is. I doubt its exceptionally useful though. – Dennis – 2017-06-23T15:21:32.810

4

C# (.NET Core), 48 43 31 bytes

(a,m,n)=>a[m]+=a[n]-(a[n]=a[m])

Try it online!

Swaps the numbers in the original array, no temporary variables used. Nonetheless I can't take credit for this answer as it has been Neil's idea.

Charlie

Posted 2017-06-22T10:28:30.630

Reputation: 11 448

@LeakyNun it does not seem to work, as that leaves a[m] with a value of 0. Try it yourself!

– Charlie – 2017-06-22T11:14:21.443

(a,m,n)=>a[m]+=a[n]-(a[n]=a[m]) seems to work though. – Neil – 2017-06-22T11:38:59.807

(These answers are all also valid in ES6 JavaScript, no?) – Neil – 2017-06-22T11:41:44.427

4

Japt, 17 16 bytes

hV(A=UgV UgW¹hWA

Try it online!

Saved a byte thanks to ETHproductions

Tom

Posted 2017-06-22T10:28:30.630

Reputation: 3 078

2Nice. Don't think you need the comma though. – ETHproductions – 2017-06-22T11:23:02.260

@ETHproductions Thanks, you're right. – Tom – 2017-06-22T11:24:33.287

Alternative 16 byte implementation but I'm still convinced there's a shorter solution. – Shaggy – 2017-06-22T12:02:29.800

215 bytes – ETHproductions – 2017-06-22T16:10:28.093

4

Common Lisp, 42 bytes

-2 bytes thanks to @coredump.

(lambda(a i j)(rotatef(elt a i)(elt a j)))

Try it online!

Quite straight forward, since there is a Common Lisp macro to swap: rotatef.

Dada

Posted 2017-06-22T10:28:30.630

Reputation: 8 279

You could use ELT instead of AREF – coredump – 2017-06-23T11:10:46.787

1@coredump Right, thanks! – Dada – 2017-06-23T11:30:17.377

4

CJam, 4 bytes

{e\}

Try it online!

Dennis

Posted 2017-06-22T10:28:30.630

Reputation: 196 637

3

Javascript ES6, 36 34 bytes

(a,m,n)=>(x=a[m],a[m]=a[n],a[n]=x)
  • -2 Bytes because the function is altering the array. No need to return the array. Thanks to @Neil

Demo

f=

(a,m,n)=>(x=a[m],a[m]=a[n],a[n]=x)

let a1=[1,2,3,4], a2=[5,8,9], a3=[11,13,15,3]

f(a1,0,1);
f(a2,0,2);
f(a3,1,2);

console.log(JSON.stringify(a1)); //[2,1,3,4]
console.log(JSON.stringify(a2)); //[9,8,5]
console.log(JSON.stringify(a3)); //[11,15,13,3]

Weedoze

Posted 2017-06-22T10:28:30.630

Reputation: 931

1Those instructions modify the array, which means you're allowed to not return the array, which will save you a few bytes. – Neil – 2017-06-22T12:14:14.563

2

Java 8, 48 bytes

(a,b,c)->{int t=a[b];a[b]=a[c];a[c]=t;return a;}

Input:

int[] a
int b
int c

Okx

Posted 2017-06-22T10:28:30.630

Reputation: 15 025

How do you do lambdas with three arguments in Java? – Leaky Nun – 2017-06-22T10:48:16.623

@LeakyNun I made a custom class for it. – Okx – 2017-06-22T10:48:44.353

The same logic (and byte count) can be achieved with currying and no custom classes. Try it online!

– Bashful Beluga – 2017-06-22T12:11:57.503

1Those instructions modify the array, which means you're allowed to not return the array, which will save you a few bytes. – Neil – 2017-06-22T12:13:59.490

@Okx could you show your code for the custom class? – Leaky Nun – 2017-06-22T13:15:25.717

1

@LeakyNun I'm not Okx, but here is a Try it now example with Okx's current answer and custom interface.

– Kevin Cruijssen – 2017-06-22T13:25:56.077

And @Neil is right, you can get rid of the return: (a,b,c)->{int t=a[b];a[b]=a[c];a[c]=t;}

– Kevin Cruijssen – 2017-06-22T13:27:32.420

1

And based on Carlos Alejo's amazing C# answer (with @Neil's help), you can make it even shorter by getting rid of the temporary variable: (a,b,c)->a[b]+=a[c]-(a[c]=a[b]) (31 bytes)

– Kevin Cruijssen – 2017-06-22T13:32:54.980

1cough cough Collections::swap is 17 bytes... at least assuming this holds for this challenge... – Socratic Phoenix – 2017-06-23T00:57:18.280

@SocraticPhoenix yep, but... the full name is java.util.Collections::swap, so 27 bytes, not 17. Go ahead, post it :) – Olivier Grégoire – 2017-06-23T11:31:07.647

@OlivierGrégoire still shorter :) – Socratic Phoenix – 2017-06-23T13:39:07.650

@SocraticPhoenix Yeah, of course, that's why I said to post it! You'll get at least one +1, mine ;) – Olivier Grégoire – 2017-06-23T13:45:27.233

2

05AB1E, 10 bytes

D²è³ǝ¹³è²ǝ

Try it online!

Okx

Posted 2017-06-22T10:28:30.630

Reputation: 15 025

2

Octave, 28 bytes

@(a,n){a(n)=a(flip(n)),a}{2}

Try it online!

Quite satisfied with this one actually :)

Takes input on the form: f([1,2,3,4],[1,2]), 1-indexed.

Explanation:

@(a,n)                         % Anonymous function that takes two 1-dimensional
                               % arrays as input
      {               , }      % Create a cell with two elements
       a(n)=a(flip(n))         % One element are the two number at indices given by
                               % the second input array. This will be a 1x2 array
      {a(n)=a(flip(n)),a}      % Place those two in a cell together with the entire array a
                               % a is now updated, thanks to Octave's inline assignment
      {a(n)=a(flip(n)),a}{2}   % Return the second element

Stewie Griffin

Posted 2017-06-22T10:28:30.630

Reputation: 43 471

2

Jellyfish, 7 bytes

p
ZRi
i

Takes a list and a pair of indices. Try it online!

Explanation

Jellyfish happens to have a "modify items at indices" function, Z, which does exactly what we need. The two is grab the inputs from STDIN. Z takes as arguments the second input, the reversal function R, and the list. Then Z performs the modification, and p prints the result.

Zgarb

Posted 2017-06-22T10:28:30.630

Reputation: 39 083

2

R, 38 bytes

function(x,a,b){x[c(a,b)]=x[c(b,a)];x}

Feels rather long, but I can't get it much shorter. Sadly it requires the explicit returning through x, requiring {} around the function body. pryr::f() doesn't recognise the need for x as function argument so doesn't work :/.

JAD

Posted 2017-06-22T10:28:30.630

Reputation: 2 898

I think function(x,i)replace(x,i,rev(i)) would work, even with pryr syntax. – Giuseppe – 2017-06-22T17:09:27.767

@Giuseppe Ah, I was looking for a convenient function to do the swap, but was searching with the wrong terms. Feel free to post that as an own answer. – JAD – 2017-06-22T19:41:54.010

@Giuseppe I think you need to do replace(x,i,x[rev(i)]), else you'll place the indices instead of their values. – JAD – 2017-06-22T20:18:51.443

2

Shenzhen I/O, 735 Bytes

23¥, 810 Power, 48 Lines of Code

[traces] 
......................
......................
......................
......................
......................
......................
.14.14.14.............
.94.14.14.............
.A........1C..........
.3554..95556..........
.9554.16..............
.A....................
.2....................
......................

[chip] 
[type] UC6
[x] 4
[y] 2
[code] 
  slx x0
  mov x1 acc
  mov x1 dat
  mov acc x3
  mov dat x3
  mov acc x3
  mov dat x3

[chip] 
[type] UC6
[x] 8
[y] 5
[code] 
  slx x2
  mov x2 x1
  mov x0 dat
  mov x2 x1
  mov x0 acc
  mov x2 x1
  mov dat 

[chip] 
[type] UC4X
[x] 2
[y] 6
[code] 
  slx x0
  mov 0 x3
j:  mov x0 acc
  mov acc x2
  teq acc 0
- jmp j
  mov -999 x1

[chip] 
[type] RAM
[x] 5
[y] 6

SIO

DISCLAIMER: Arrays are 0-terminated in this. Arrays are a pain in the ass to work with in Shenzhen I/O otherwise.

I actually made a steam level for this game. You can play it here.

EDIT: Aaand I just realized I said that the array in was ordered. Heck.

junkmail

Posted 2017-06-22T10:28:30.630

Reputation: 131

Welcome to the site This is really cool! do you think that you might be able to remove some of the whitespace in the file and still have Shenzhen IO accept the file? I don't know how much you have fiddled with it, but you should try and see how flexible the format is. – Post Rock Garf Hunter – 2017-06-25T02:26:56.783

I haven't played around with it! On the other hand, I am axing the header for the puzzle which contains the puzzle name and solution name, so I dunno if I should bother. – junkmail – 2017-06-25T02:33:48.407

1

Mathematica, 32 bytes

(a=#;a[[{##2}]]=a[[{#3,#2}]];a)&

alephalpha

Posted 2017-06-22T10:28:30.630

Reputation: 23 988

3a[[{##2}]]==a[[{#3,#2}]] should be a[[{##2}]]=a[[{#3,#2}]] (using Set, not Equals) – JungHwan Min – 2017-06-22T13:12:48.863

1

Swift, 111 65 bytes (0-indexed)

Swift is already notorious for being one of the worst code-golf languages, but here is a function that makes use of ternary expressions:

func t(l:[Int],m:Int,n:Int){var r=l;r[m]=l[n];r[n]=l[m];print(r)}

Check it out! - Usage: t(l:[1,2,3],m:0,n:1).

Mr. Xcoder

Posted 2017-06-22T10:28:30.630

Reputation: 39 774

Using a default param for r would save you bytes and you can also just mutate the passed array (AFAIK swift array are pass by value) – Downgoat – 2017-06-22T16:55:23.557

Default parameter in Swift? How can I do that? – Mr. Xcoder – 2017-06-22T17:40:44.837

And parameters are constants in Swift @Downgoat – Mr. Xcoder – 2017-06-22T17:41:09.763

1

k (kona), 13 bytes

{x[y]:x@|y;x}

Pretty basic, but it works. Ex:

k){x[y]:x@|y;x}[1 2 3 4; 0 1]
2 1 3 4

Simon Major

Posted 2017-06-22T10:28:30.630

Reputation: 401

1

Perl 5, 32 bytes

-3 bytes thanks to @Dom Hastings!

30 bytes of code + -pa flags.

@F[pop@p,@p]=@F[@p=<>];$_="@F"

Try it online!

Quite straight forward, using array slices.

Dada

Posted 2017-06-22T10:28:30.630

Reputation: 8 279

Hey hey, tinkered with this a little and managed to save 3 bytes! @F[pop@p,@p]=@F[@p=<>];$_="@F". – Dom Hastings – 2017-06-22T13:27:50.450

@DomHastings Hmm, nice, as always! Thanks :) – Dada – 2017-06-22T13:35:52.777

1

C, 42 bytes

Modify the array in place with a temp value.

f(r,m,n){int*a=r;r=a[m];a[m]=a[n];a[n]=r;}

C, 60 58 bytes

A little more interesting, not using any temp value...

f(a,m,n)int*a;{a[m]+=a[n];a[n]-=a[m];a[n]*=-1;a[m]-=a[n];}

C, 49 bytes

Using XOR

f(a,m,n)int*a;{a[m]^=a[n];a[n]^=a[m];a[m]^=a[n];}

cleblanc

Posted 2017-06-22T10:28:30.630

Reputation: 3 360

Heh, I was just about to post f(x,i,j,t)int*x;{t=x[i];x[i]=x[j];x[j]=t;}. – Dennis – 2017-06-22T13:47:06.613

@Dennis you saved me two bytes on the other solution, thanks! – cleblanc – 2017-06-22T14:00:05.580

Wouldn't the second solution be shorter (and safer) with ^? – Dennis – 2017-06-22T14:10:00.720

-1 for the XOR version using a define instead of a function #define X(x,y,z)x[y]^=x[z],x[z]^=x[y],x[y]^=x[z] – Giacomo Garabello – 2017-06-22T14:55:30.533

f(r,m,n){int*a=r;r=a[m];a[m]=a[n];a[n]=r;} is broken: SIGSEGV. – Bodo Thiesen – 2017-06-22T20:25:03.403

@BodoThiesen compile it for 32bits with -m32 Try it online!

– cleblanc – 2017-06-22T20:28:53.397

-m32 only works if there is a 32 bit mode available. So, you should at least clarify, that your solution is a x86_32 only solution. – Bodo Thiesen – 2017-06-22T20:48:23.393

1

Pyth, 17 8 bytes

Saved 9 bytes thanks to Leaky Num.

@LQ.rUQE

Test it online!

This is 0-indexed, and the indices are provided as a tuple: (n, m).

Explanations

@LQ.rUQE

     UQ     # Generate [0, 1, 2, ..., len(input)]
       E    # Get the indices as the tuple (1, 2)
   .r       # Translate each element of UQ to its cyclic successor in E
            # Now the indices are permuted (e.g. [0, 2, 1, ..., len(input)]
@LQ         # For each index, get it's value. Implicit print

Jim

Posted 2017-06-22T10:28:30.630

Reputation: 1 442

8 bytes: @LQ.rUQE

– Leaky Nun – 2017-06-22T16:49:12.643

@LeakyNun It's so different I think you can post it for yourself! – Jim – 2017-06-22T16:50:04.073

I'm the OP; I don't post on my own challenge. – Leaky Nun – 2017-06-22T16:50:20.087

1

Mathematica, 20 bytes

#~Permute~Cycles@#2&

Pure function taking two arguments in the following 1-indexed (and possibly abusive) format: the second test case [5,8,9]; 0 2; [9,8,5] would be called as

#~Permute~Cycles@#2& [ {5,8,9} , {{1,3}} ]

(spaces are extraneous and just for visible parsing). Permute is the builtin function that applies a permutation to a list, and Cycles[{{a,b}}] represents the permutation that exchanges the ath and bth elements of a list and ignores the rest.

Greg Martin

Posted 2017-06-22T10:28:30.630

Reputation: 13 940

What do the ~ do? – Cyoce – 2017-06-23T03:54:21.263

~ is Mathematica's infix notation for a binary function: x~f~y means the same thing as f[x,y]. – Greg Martin – 2017-06-23T07:35:14.940

1

x86 Machine Code, 10 bytes

8B 04 8B 87 04 93 89 04 8B C3

This is a function written in 32-bit x86 machine code that swaps the values at the specified indices in a given array. The array is modified in-place, and the function does not return a value.

A custom calling convention is used, requiring the function's parameters to be passed in registers:

  • The address of the array (pointer to its first element) is passed in the EBX register.
  • The zero-based index of element A is passed in the ECX register.
    (Assumed to be a valid index.)
  • The zero-based index of element B is passed in the EDX register.
    (Assumed to be a valid index.)

This keeps the size down and complies with all formal requirements, but does mean that the function cannot be easily called from other languages like C. You'd need to call it from another assembly-language program. (You could rewrite it to use any input registers, though, without affecting the byte count; there's nothing magical about the ones I chose.)

Ungolfed:

8B 04 8B     mov  eax, DWORD PTR [ebx+ecx*4]   ; get value of element A
87 04 93     xchg eax, DWORD PTR [ebx+edx*4]   ; swap element A and element B
89 04 8B     mov  DWORD PTR [ebx+ecx*4], eax   ; store new value for element A
C3           ret                               ; return, with array modified in-place

Cody Gray

Posted 2017-06-22T10:28:30.630

Reputation: 2 639

1

R, 34 bytes

pryr::f(`[<-`(a,c(m,n),a[c(n,m)]))

Sven Hohenstein

Posted 2017-06-22T10:28:30.630

Reputation: 2 464

1

Java 8 + InverseY, 27 bytes

java.util.Collections::swap

Just calls the swap function... this is a method reference of the type Consumer3<List, Integer, Integer>.

Try it online! (header and footer for boilerplate & copy of Consumer3 interface)

Socratic Phoenix

Posted 2017-06-22T10:28:30.630

Reputation: 1 629

You don't need to add " + InverseY". It's valid in vanilla Java 8. – Olivier Grégoire – 2017-06-23T15:57:56.067

1

JavaScript (ES2015), 66 57 49 bytes

A different (alas, longer) approach than previous JavaScript answers

(s,h,o,w=s.splice.bind(s))=>w(h,1,...w(o,1,s[h]))

Source

const swap = (arr, a, b, splice) => {
  splice(a, 1, ...splice(arr[b], 1, arr[a]))
}

sshow

Posted 2017-06-22T10:28:30.630

Reputation: 133

1(s,h,o,w=s.splice.bind(s))=>w(h,1,...w(o,1,s[h])) 49 bytes – Patrick Roberts – 2017-06-24T03:05:37.803

Forgot about them default args. Thanks! – sshow – 2017-06-24T23:58:57.007

0

awk, 31 bytes

{c=$a;$a=$b;$b=c;a=$1;b=$2}NR>1

Try it online!

Takes input in the format

1 2
1 2 3 4

and outputs as

2 1 3 4

(1-indexed).

Explanation

The entire program is a missing pattern with an action followed by a pattern with a missing action.

Since a missing pattern runs on each line, the code inside the braces runs for both input lines. The c=$a;$a=$b;$b=c; part swaps the two values at indices a and b (through the temporary variable c). This only has an effect on the second line, since on the first line a and b are not yet defined. The a=$1;b=$2 part defines a to be the first field and b to be the second field, which sets the appropriate values for the first part to run on the second line.

Since a missing action is equivalent to {print}, the pattern prints every line it matches. This pattern in particular is NR>1: that is, print whenever the line number is greater than 1, which happens to be line 2. This runs after the swapping of values has taken place, thus completing the task.

Doorknob

Posted 2017-06-22T10:28:30.630

Reputation: 68 138

0

Japt, 15 bytes

£gY¶V?W:Y¶W?V:Y

Test it


Explanation

       :Implicit input of array U and integers V & W
£      :Map over the array (with Y being the index of the current element), replacing each element with...
g      :  The element in the array at index...
Y¶V?W  :    W, if Y equals V
:Y¶W?V :    or V, if Y equals W
:Y     :    or just Y otherwise
       :Implicit output of modified array

Shaggy

Posted 2017-06-22T10:28:30.630

Reputation: 24 623

Nice technique, looks a little verbose though... but I can't find a way to golf it. – ETHproductions – 2017-06-22T16:52:42.270

@ETHproductions: yeah, I'm still convinced there's a shorter way, just haven't had the time to come back and find it and it looks like I won't until tomorrow :( – Shaggy – 2017-06-22T16:54:29.217

0

q/kdb+, 17 bytes

Solution:

{@[x;(|)y;:;x y]}

Example:

q){@[x;(|)y;:;x y]}[1 2 3 4;0 1]
2 1 3 4

Explanation:

A q version of the k answer by Simon. Apply the assign : function to x at indices reverse-y with value of x indexed at y. Broken down you can see more clearly:

q)x:1 2 3 4
q)y:0 1
q)x y
1 2
q)(|)y
1 0
q)x(|)y
2 1
q)@[x;(|)y;:;x y]
2 1 3 4

streetster

Posted 2017-06-22T10:28:30.630

Reputation: 3 635

0

Powershell, 64 49 bytes

$f=$args;$t=$f[0];($t[$f[1]],$t[$f[2]]=$t[$f[2]],$t[$f[1]])>$;$t

param($a,$b,$c)($a[$b],$a[$c]=$a[$c],$a[$b])>$;$a

At least somewhat better solution.

Also I have no idea why redirecting to $ even works ^^

whatever

Posted 2017-06-22T10:28:30.630

Reputation: 161

0

V, 10 bytes

ÀGYÀGVpVp

Try it online!

This takes input with each number to a line, and indices as program arguments. 1-indexed.

James

Posted 2017-06-22T10:28:30.630

Reputation: 54 537

0

Julia 0.5, 20 bytes

x*t=x[t]=x[t[[2,1]]]

Try it online!

Dennis

Posted 2017-06-22T10:28:30.630

Reputation: 196 637

-1

C, 42 bytes (one extra argument on function call)

f(a,m,n,t)int*a;{t=a[m];a[m]=a[n];a[n]=t;}

Try it online

C, 44 bytes

f(a,m,n)int*a;{int t=a[m];a[m]=a[n];a[n]=t;}

Bodo Thiesen

Posted 2017-06-22T10:28:30.630

Reputation: 121