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 code-golf. Shortest answer in bytes wins. Standard loopholes apply.
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
andn
be taken as an array? – Okx – 2017-06-22T11:23:36.523Can 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
andn
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