| Bytes | Lang | Time | Link |
|---|---|---|---|
| 068 | SAKO | 250326T174843Z | Acrimori |
| 074 | Tcl | 211201T121811Z | sergiol |
| 028 | Zsh | 241218T072558Z | roblogic |
| 004 | J | 241216T034646Z | south |
| 035 | Dart | 241215T112316Z | Dmytro R |
| 035 | C# Visual C# Compiler | 241215T003359Z | sergiol |
| 058 | C# Visual C# Compiler | 211201T131652Z | sergiol |
| 003 | Uiua | 231105T190920Z | chunes |
| 008 | Pip xp | 211015T175705Z | DLosc |
| 010 | BQN | 211227T115747Z | Dominic |
| 001 | MathGolf | 211202T074520Z | Kevin Cr |
| 036 | AWK | 211201T145946Z | Pedro Ma |
| 036 | C++ gcc | 211201T124231Z | sergiol |
| 049 | Desmos | 211110T071020Z | Aiden Ch |
| 006 | ErrLess | 211023T081330Z | Ruan |
| 018 | Raku | 211017T172950Z | Sean |
| 027 | Clojure | 211018T162947Z | NikoNyrh |
| 030 | Ruby | 211019T094405Z | DrQuariu |
| 021 | Factor | 211015T223721Z | chunes |
| 004 | CJam | 211015T195126Z | Luis Men |
| 042 | Perl 5 | 211015T203407Z | plentyof |
| 007 | x8616 machine code | 211018T011247Z | 640KB |
| 034 | Pari/GP | 211018T033318Z | alephalp |
| 004 | 05AB1E | 211017T170221Z | Kevin Cr |
| 038 | Javascript | 211017T160418Z | William |
| 205 | Lean | 211016T225801Z | user |
| 158 | Core Maude | 211017T021452Z | Chris Bo |
| 034 | Kotlin | 211016T210723Z | busukxua |
| 034 | Icon | 211016T072203Z | Galen Iv |
| 033 | TIBasic | 211015T222601Z | Youserna |
| 021 | Wolfram Language Mathematica | 211015T194240Z | Michael |
| 049 | Python 2 | 211016T042201Z | Akshay S |
| 049 | Python 3 | 211016T112031Z | Stephen |
| 011 | Rust | 211016T085545Z | alephalp |
| 033 | Red | 211016T071457Z | Galen Iv |
| 005 | stacked | 211015T225626Z | Conor O& |
| 031 | JavaScript | 211015T151805Z | Unmitiga |
| 038 | C++ | 211015T161210Z | Unmitiga |
| 034 | C clang | 211015T181113Z | Noodle9 |
| 099 | Retina 0.8.2 | 211015T162754Z | Neil |
| 014 | Charcoal | 211015T160236Z | Neil |
| 122 | BrainFlak | 211015T154448Z | Wheat Wi |
| 007 | Vyxal | 211015T155207Z | Aaroneou |
| 032 | Python 2 | 211015T151159Z | pxeger |
| 005 | APL Dyalog Unicode | 211015T153850Z | ovs |
| 005 | Jelly | 211015T153150Z | caird co |
| 046 | PHP | 211015T153813Z | Kaddath |
| 039 | Zsh | 211015T153652Z | pxeger |
| 007 | Jelly | 211015T153637Z | hyperneu |
| 031 | R | 211015T152741Z | pajonk |
| 027 | Java | 211015T152426Z | Unmitiga |
| 020 | Julia 1.0 | 211015T152224Z | MarcMush |
| 056 | Haskell | 211015T151116Z | Wheat Wi |
| 049 | Python 2 | 211015T150624Z | Twilight |
SAKO, 68 bytes
PODPROGRAM:(*A)=S(*A,K,O)
CALKOWITE:K,O
C=A(K)
A(K)=A(O)
A(O)=C
WROC
Very simple solution that takes an array (A) and two integers (K, O) as arguments to a subroutine (S()), and swaps them using a temporary variable C.
To make it more interesting I made it spell out SAKO in the subroutine definition.
Interestingly, declaration STRUKTURA isn't needed, as we operate only on given indexes in an array of known type, so specifyin its size isn't obligatory.
Tcl, 74 bytes
proc S {L a b} {lset M $a [lindex [set M $L] $b]
lset M $b [lindex $L $a]}
proc S {L a b} {set x [lindex $L $a]
lset L $a [lindex $L $b]
lset L $b $x}
J, 4 bytes
C.~<
Input is L f (a b). The function is a dyadic hook.
C.~<
< NB. box y
C.~ NB. apply a permutation in cycle form (C.) with the arguments swapped (~)
C. fills in the incomplete permutation according to the identity permutation, thus, the items are swapped and everything else is left alone.
I suppose if a b could be given as a boxed list, then an improvement could be made by allowing the answer to be C. alone (meaning the input is given as (<a b) f L).
Dart, 35 bytes
(l,a,b)=>[...l]..[a]=l[b]..[b]=l[a]
Ungolfed:
List<dynamic> s(List<dynamic> l, int a, int b) =>
[...l] // copy array
..[a] = l[b] // set b value from original to a pos
..[b] = l[a]; // and opposite
C# (Visual C# Compiler), 35 bytes
(L,a,b)=>{(L[a],L[b])=(L[b],L[a]);}
based on my own answer, mixed with the lambda idea from the @KevinCruijssen 's idea on his comment there.
C# (Visual C# Compiler), 58 bytes
void f<T>(List<T> L,int a,int b){(L[a],L[b])=(L[b],L[a]);}
Pip -xp, 8 bytes
aRAba@Rb
Takes input as two command-line arguments: the list, and a list containing the two indices (0-based). Attempt This Online!
Explanation
The -x flag is for taking the arguments as lists rather than strings; the -p flag is for displaying the result as a list rather than concatenated together.
a ; In the first argument
RA ; replace the items at indices given by
b ; the second argument
a ; with the values in the first argument
@ ; at indices
Rb ; reverse(second argument)
The straightforward version, which takes the indices as separate arguments, comes in at 9 bytes:
a@b::a@ca
:: ; Swap
a@b ; the item in a at index b
a@c ; with the item in a at index c
a ; Output the new value of a
BQN, 18 10 bytes
Edit: -8 bytes thanks to Razetime
{⌽⌾(𝕨⊸⊏)𝕩}
Probably not the tersest code, but it works, which was no trivial accomplishment for my very limited BQN ability. Now quite short...
Will try to golf-down better as my abilities (gradually) improve. ...thanks to Razetime.
Swap ← {⌽⌾(𝕨⊸⊏)𝕩} # define Swap function:
# list of 2 indices to swap on left = 𝕨
# array on right = 𝕩.
⌾ # 'under' = apply function on LHS
# to elements specified by RHS
(𝕨⊸⊏) # RHS: elements of 𝕩 at indices 𝕨
⌽ # LHS: reverse
MathGolf, 1 byte
µ
Apparently MathGolf has a builtin for this. Came across it in the docs when I was working on another challenge today. ¯\_(ツ)_/¯.
Takes the loose index-inputs before the list.
AWK, 36 bytes
$$(NF-1)+=$$NF-($$NF=$$(NF-1)),NF-=2
Expected input
The input is a list of integers separated by spaces; the last two integers are the indexes of the values that must be swapped:
Input:
3 8 1 4 10 10 10 10 1 6
\_________________/ | |
List of integers, | L> Second index
starting index at 1 |
L> First index
Output:
10 8 1 4 10 3 10 10
| |
\___________/
Swapped
How it works
$$(NF-1) We take the integer which index is the value of the second-to-last integer,
+= and add:
$$NF the integer which index is the last integer
-($$NF minus itself,
=$$(NF-1)) except that it is now the integer which index is the second-to-last integer.
,NF-=2 And let's remove the last two integers.
Phew! It should print the modified input, at last.
It uses this swapping oneliner: a+=b-(b=a).
For better understanding: NF is the variable for the number of fields, i.e, the number of integers in the input. $n is the nth integer in the input, so $NF is the last integer, and $(NF-1) the second-to-last integer. $$NF equals $($NF), that is the integer which index is the last integer.
NF-=2 reduces the number of fields by two, ignoring the two indexes.
Desmos, 49 bytes
l=[1...L.length]
f(L,a,b)=\{l=a:L[b],l=b:L[a],L\}
Try It On Desmos! - Prettified
Surprisingly readable (if you know a bit of Desmos) even after I code golfed it.
Python Equivalent (switching to 0-based)
def f(L,a,b):
returnList = []
for l in range(len(L)):
if l == a:
returnList.append(L[b])
elif l == b:
returnList.append(L[a])
else:
returnList.append(L[l])
return returnList
ErrLess, 6 bytes
0m:r.M
A macro.
Explanation
0 { Push a 0 to the stack to identify the macro }
m { Start macro definition }
: { (L a b) -> (L (a b)) }
r { Rotate }
. { Halt (Return) }
M { End macro definition }
You can test it with the following program:
0m
:r.
M
{ Test cases: }
1,2x3x4x5x6x7x8x9xax 3 7
0" # a? { Outputs "(1 2 3 8 5 6 7 4 9 10)" and a newline }
3,8x1x4xaxaxaxax 0 5
0" # a? { Outputs "(10 8 1 4 10 3 10 10)" and a newline }
5,1x4x2x3x 0 4
0" # a? { Outputs "(3 1 4 2 5)" and a newline }
5,6x 0 1
0" # a? { Outputs "(6 5)" and a newline }
2,2x2x 0 1
0" # a? { Outputs "(2 2 2)" and a newline }
.
Raku, 19 18 bytes
{@^a[@^i].=rotate}
0-based indexing. Modifies the list in-place. Takes the indices as a two-element list.
Edit: rotate has the same effect as reverse and is one character shorter. D'oh!
Clojure, 27 bytes
#(assoc % %2(% %3)%3(% %2))
The first argument % is a vector of numbers (not a list!) so that we don't need to use the function nth.
Edit: TIO
Edit 2: And actually you cannot assoc a list anyway.
Ruby, 30 bytes
->(l,a,b){l[a],l[b]=l[b],l[a]}
Mutates the input in-place. Direct port of @pxeger's approach including the link below:
Factor, 21 bytes
[ [ exchange ] keep ]
It's almost a built-in, but exchange has stack effect ( m n seq -- ) so we need keep to actually keep the sequence around on the data stack. 0-indexed.
CJam, 4 bytes
{e\}
Code block (analogous to a function) that pops three elements from the stack: L, a, b, and pushes the swapped version of L. Indices a, b are 0-based.
Explanation
{ } e# Define code block
e\ e# Swap elements in array
Header:
q e# Read all input as an unevaluated string, and push it to the stack
~ e# Evaluate string. Gives an array and two numbers, that are pushed
Footer:
~ e# Execute block
p e# Print string representation of the top of the stack
Perl 5, 42 bytes
Updated TIO link to show positive indices only per challenge instructions (thanks, Kevin!)
sub a{($a,$b,$l)=@_;@$l[$a,$b]=@$l[$b,$a]}
Takes arguments as (first index, second index, 0-bound array). Mutates array in-place. Works with arrays containing any valid values, not just positive integers!
x86-16 machine code, 7 bytes
00000000: 8a01 8600 8801 c3 .......
Listing
8A 01 MOV AL, BYTE PTR[BX][DI] ; put 'b' value into AL
86 00 XCHG AL, BYTE PTR[BX][SI] ; swap 'b' value with 'a' position
88 01 MOV BYTE PTR[BX][DI], AL ; put 'a' value into 'b' position
C3 RET ; return to caller
Input \$L\$ at [BX], indices \$a\$ in SI, \$b\$ in DI, 0-based.
A test with our old friend DOS DEBUG:
05AB1E, 4 bytes
è¹Rǝ
Since no one posted an 05AB1E answer yet and it's been a couple of days, I'm gonna post my prepared 4-byter.
First input is a pair of indices \$[a,b]\$, second input is the list \$L\$.
Try it online or verify all test cases.
Explanation:
è # Index the first (implicit) input into the second (implicit) input-list
¹ # Push the first input-indices again
R # Reverse them
ǝ # Insert the values at those reversed indices into the (implicit) second input-list
# (after which the result is output implicitly)
Javascript 38 bytes
(l,a,b)=>(l[a]=[l[b],l[b]=l[a]][0])&&l
Lean, 211 205 bytes
Helper:
notation `L`:=list ℕ
structure R:=m::(A:L)(B:ℕ)(C:L)
def r:L->L->ℕ->R
|p(h::t)0:=R.m p h t
|p(h::t)(n+1):=r(p++[h])t n
|_[]_:=R.m[]0[]
Actual function:
λl a b,let f:=r[]l a,z:=r[]f.C(b-a-1)in f.A++z.B::z.A++f.B::z.C
There's got to be a way to make product types and define type aliases easily, but I couldn't find it.
Core Maude, 158 bytes
mod S is pr ARRAY{Nat,Nat0}*(sort Array{Nat,Nat0}to A). var I J X Y : Nat . op
s : A Nat Nat -> A . eq s(A:A,I,J)= insert(I,A:A[J],insert(J,A:A[I],A:A)). endm
Example Session
\||||||||||||||||||/
--- Welcome to Maude ---
/||||||||||||||||||\
Maude 3.1 built: Oct 12 2020 20:12:31
Copyright 1997-2020 SRI International
Sat Oct 16 22:01:13 2021
Maude> mod S is pr ARRAY{Nat,Nat0}*(sort Array{Nat,Nat0}to A). var I J X Y : Nat . op
> s : A Nat Nat -> A . eq s(A:A,I,J)= insert(I,A:A[J],insert(J,A:A[I],A:A)). endm
Maude> red s(0 |-> 1 ; 1 |-> 2 ; 2 |-> 3 ; 3 |-> 4 ; 4 |-> 5 ; 5 |-> 6 ; 6 |-> 7 ;
> 7 |-> 8 ; 8 |-> 9 ; 9 |-> 10, 3, 7) .
result A: 0 |-> 1 ; 1 |-> 2 ; 2 |-> 3 ; 3 |-> 8 ; 4 |-> 5 ; 5 |-> 6 ; 6 |-> 7 ;
7 |-> 4 ; 8 |-> 9 ; 9 |-> 10
Maude> red s(0 |-> 3 ; 1 |-> 8 ; 2 |-> 1 ; 3 |-> 4 ; 4 |-> 10 ; 5 |-> 10 ; 6 |-> 10 ;
> 7 |-> 10, 0, 5) .
result A: 0 |-> 10 ; 1 |-> 8 ; 2 |-> 1 ; 3 |-> 4 ; 4 |-> 10 ; 5 |-> 3 ; 6 |->
10 ; 7 |-> 10
Maude> red s(0 |-> 5 ; 1 |-> 1 ; 2 |-> 4 ; 3 |-> 2 ; 4 |-> 3, 0, 4) .
result A: 0 |-> 3 ; 1 |-> 1 ; 2 |-> 4 ; 3 |-> 2 ; 4 |-> 5
Maude> red s(0 |-> 5 ; 1 |-> 6, 0, 1) .
result A: 0 |-> 6 ; 1 |-> 5
Maude> red s(0 |-> 2 ; 1 |-> 2 ; 2 |-> 2, 0, 1) .
result A: 0 |-> 2 ; 1 |-> 2 ; 2 |-> 2
Ungolfed
mod S is
pr ARRAY{Nat,Nat0} * (sort Array{Nat,Nat0} to A).
var I J X Y : Nat .
op s : A Nat Nat -> A .
eq s(A:A, I, J) = insert(I, A:A[J], insert(J, A:A[I], A:A)) .
endm
The answer is obtained by reducing the function s with the list, given as a Maude array (e.g., 0 |-> 1 ; 1 |-> 2 for [1, 2]), and the two indices, zero-indexed.
Maude does have lists (e.g., 0 1 for the same list [1, 2]), but this is one case where it's actually shorter to use arrays (which are generally very verbose) because we don't need to use an array literal syntax in the code, and because we need indexing. The FAQ says it's allowed to accept input as either an array or a list.
Kotlin, 34 bytes
{l,x,y->l[x]=l[y].also{l[y]=l[x]}}
Ungolfed:
{ l, x, y ->
l[x] = l[y].also { l[y] = l[x] }
}
This answer is a bit of an idiom in Kotlin.
Any#also() basically executes the given function, but then returns the receiver. In this case, the outer l[y] is evaluated, then .also() runs the lambda { l[y] = l[x] }, and returns the old value of l[y].
TI-Basic, 39 33 bytes
Prompt L,A,B
ʟL(A→X
ʟL(B→ʟL(A
X→ʟL(B
ʟL
-6 bytes thanks to MarcMush.
Input indices are 1-based. Output is stored in Ans and is displayed.
Wolfram Language (Mathematica), 24 21 bytes
1-based indices, input is a list and a tuple of indices to reverse
Reverse~SubsetMap~##&
-3 bytes thanks to att.
Python 2, 52 49 bytes
(longer than the approach by @pxeger, but doesn't mutate in-place
lambda a,b,l:l[:a]+[l[b]]+l[a+1:b]+[l[a]]+l[b+1:]
EDIT: Thanks @Stephen Universe for saving me few bytes!
56 bytes by using list.pop and list.insert:
def f(a,b,l):l.insert(b,l.pop(a)),l.insert(a,l.pop(b-1))
stacked, 5 bytes
$exch
You can remove the $ if input is allowed to be taken from the stack for 4 bytes. Convenient builtin to be sure.
22 bytes
[@j@i[i j nswap]apply]
Function. nswap performs a stack operation of swapping the ith and jth members, so we simply pop i and j and treat the stack at the top of the stack as the stack for nswap.
JavaScript, 31 bytes
l=>a=>b=>l[a]^=l[b]^(l[b]=l[a])
Only works for integers.
Thanks to Arnauld.
JavaScript, 32 bytes
l=>a=>b=>[l[a],l[b]]=[l[b],l[a]]
C++, 51 46 38 bytes
#define f(a,i,j)a[i]^=a[j]^(a[j]=a[i])
Saved 5 bytes thanks to Kevin Cruijssen.
Saved 8 bytes thanks to AZTECCO.
Retina 0.8.2, 99 bytes
2`\d+
$*
1*(,1*);
$1,$&
(?<=(?=.*;(?<-2>\d+,)*(\d+))(1)*,(?(4)$)(?<-4>1)*(,1*)?;(\d+,)*)\d+
$1
.*;
Try it online! Link includes test cases. Takes input in the form a,b;L. Explanation:
2`\d+
$*
Convert the indices to unary.
1*(,1*);
$1,$&
Make a second copy of b so that we now have b,a,b;L.
(?<=(?=.*;(?<-2>\d+,)*(\d+))(1)*,(?(4)$)(?<-4>1)*(,1*)?;(\d+,)*)\d+
$1
Match an integer in L, with index $#4 equalling either a or b (using a .NET balancing group), then match the other index in $#2, and match the integer at that index as the replacement for this integer (also using a .NET balancing group).
.*;
Delete a and b.
Charcoal, 14 bytes
IEθ⎇№ηκ§θ⁻Σηκι
Try it online! Link is to verbose version of code. Takes the 0-indexed indices as a 2-element array. Explanation:
θ Input array
E Map over elements
№ Count of
κ Current index in
η Input indices
⎇ If found then
θ Input array
§ Indexed by
η Input indices
Σ Take the sum
⁻ Minus
κ Current index
ι Else current element
I Cast to string
Implicitly print
Brain-Flak, 122 bytes
(([{}]{()<({}[()]<({}<>)<>>)>}{})<(({}({}))([{}]{})<{({}()<<>({}<>)>)}{}>)>())<>({}<<>{({}[()]<({}<>)<>>)}{}>){<>({}<>)}{}
Works with all integers, 138 bytes
(([{}]{()<({}[()]<({}<>)<>>)>}{})<(({}({}))([{}]{})<{({}()<<>({}<>)>)}{}>)>())<>({}<<>{({}[()]<({}<>)<>>)}{}>)<>([]){({}[()]<({}<>)<>>)}<>
The difference here is that while the first uses
{<>({}<>)}{}
To pull all the items from the off stack onto the on stack this one has to use
<>({}){({}[()]<({}<>)<>>)}<>
The first one pulls until it hits a zero and then stops, so this will fail to produce the correct result when there is a zero before the first swapped value. The second checks the height and pulls that many times, thus it will work for any list.
Vyxal, 7 bytes
İṘZ(n÷Ȧ
This could almost certainly be a bit smaller, but I got smol brain and can't think of a good way to swap values.
Explanation:
İ # Get the values at the indexes
Ṙ # Reverse the values
Z # Zip the values with the new indexes
(n # For each value/index pair:
÷ # Split the value/index
Ȧ # Put the value at that index
Python 2, 32 bytes
def f(a,b,l):l[a],l[b]=l[b],l[a]
Mutates the input in-place.
26 bytes with a NumPy array:
def f(l,a):l[a[::-1]]=l[a]
APL (Dyalog Unicode), 5 bytes
1-indexed. Reverse the sublist at the indices given by the second input of the first input.
⌽@⎕⊢⎕
Jelly, 7 5 bytes
œPżịF
Takes indexes as 1 indexed and reversed (so [b, a]), the Footer on TIO does this for you.
How it works
œPżịF - Main link. Takes indices I on the left, array A on the right
œP - Partition A at the indices in I, not keeping the borders
ị - Retrieve the elements of A at the indices in I; [A[b], A[a]]
ż - Zip together
F - Flatten
PHP, 46 bytes
fn(&$a,$i,$j)=>[$a[$i],$a[$j]]=[$a[$j],$a[$i]]
changes the array in place, 0 indexing
My first shot was with list, but PHP has array destructuring since 7.1, so it ends up like the JS answer with lots of dollars (money money money!)
Zsh, 39 bytes
eval "t=$`<i`;`<i`=$`<j`;`<j`=$"t <<<$@
Takes the array on the command line, with the two indices in files called i and j.
A bit of quote trickery to avoid escapes.
Jelly, 7 bytes
,U$yJ}ị
A totally different Jelly 7-byter, so I figured I'd post this too. This is 1-indexed.
,U$yJ}ị Main link; take indices on the left
,U$ Pair the indices with the reverse of itself ([[a, b], [b, a]])
y Apply this as a translation to
J} The indices of the right list (J takes a list of length L and returns [1, 2, ..., L])
ị Index back into the original list
R, 31 bytes
Or R>=4.1, 24 bytes by replacing the word function with \.
function(L,A){L[A]=L[rev(A)];L}
Takes input as a vector and a vector of two 1-based indices.
Haskell, 56 bytes
(?)=splitAt
(x!y)z|(q,d:e)<-y?z,(a,b:c)<-x?q=a++d:c++b:e
splitAt breaks the list into two parts at the particular index. This is useful because unlike (!!) we can get all the parts first.
To start we split at the second element, then the first. Splitting at the second first means we don't have to do extra arithmetic do calculate the offset which is required if we split at the first.
We use a pattern match to then get the first element of various pieces.
