Challenge
Let's have a list L of n elements. The task is to swap every two elements in this list.
Constraints
- The list
Lhas at least two elements - Size of the list
Lis a multiple of two (i.e. number of elements is even)
Example
Input:
[1,2,3,4,5,6]Output:
[2,1,4,3,6,5]Input:
[0,1,0,1]Output:
[1,0,1,0]
Rules
- This is code-golf challenge, so the shortest code wins
- Standard rules apply for your answer with default I/O rules, so you are allowed to use stdin/stdout, functions/method with the proper parameters and return-type, full programs
- Default Loopholes are forbidden.
92 Answers 92
><>, (削除) 4 (削除ここまで) 3 bytes
i#o
Lol, ><> (削除) ties with (削除ここまで) beats Jelly & 05AB1E. Terminates with an error.
-1 thanks to @Manny Queen.
How does it work?
The instruction pointer (IP) is currently moving right
i Take input as a character
# Reflect - The IP starts moving left
i Take input again
o Output that
# Reflect - The IP starts moving right again
o Output the first input we took - the inputs are now swapped
And now, we're moving left and back at the start again on i + moving right.
This loops forever (i.e. until erroring when we're out of input)
because there is no halt instruction (;)
This is essentially executing "iioo" in an infinite loop.
-
\$\begingroup\$ no longer beats Vyxal \$\endgroup\$avarice– avarice2021年11月11日 08:36:09 +00:00Commented Nov 11, 2021 at 8:36
-
\$\begingroup\$ @wasif Oh well, still beats Jelly and osabie. \$\endgroup\$emanresu A– emanresu A2021年11月11日 09:14:06 +00:00Commented Nov 11, 2021 at 9:14
Python 3, 34 bytes
f=lambda l:l and l[1::-1]+f(l[2:])
When l is empty (which makes it falsy), return it directly. Otherwise, reverse the first two elements and make a recursive call for the rest.
-
1\$\begingroup\$ What does the r flag do? \$\endgroup\$ZippyMagician– ZippyMagician2021年11月10日 17:49:18 +00:00Commented Nov 10, 2021 at 17:49
-
3\$\begingroup\$ @ZippyMagician The
rflag makes all commands take their arguments in reverse order. That doesn't affectysince it only has one argument, but it does affectY, meaning that the program is essentially equivalent toy$Y, which swaps the halves before interleaving. \$\endgroup\$Aaroneous Miller– Aaroneous Miller2021年11月10日 17:53:43 +00:00Commented Nov 10, 2021 at 17:53
-
\$\begingroup\$
f=concatMap(reverse.take 2).iterate(drop 2)\$\endgroup\$Roman Czyborra– Roman Czyborra2021年11月22日 21:13:57 +00:00Commented Nov 22, 2021 at 21:13 -
2
convey, 7 bytes
I knew I should have implemented SpaceChem's flipflop operator, then this would be 5 bytes. :-)
-6 byte by @Manny Queen
}?{
}~1
{ puts the input list on the conveyor, } prints the result. On the ? the elements try to go down if they can. On the ~ they will wait for 1 tick before going to the output, thus starting with the first item, every second element is delayed for two ticks.
13 bytes
},<
{@^
0"
1^
The lower loop 0"1円^ copies 0 1 0 1 ... into choose @. The input is thus split into two paths. The right one takes a little bit longer, so the other number can overtake it before joining , again.
-
\$\begingroup\$ The second one can be made shorter with some rearrangement. \$\endgroup\$m90– m902021年11月11日 06:56:23 +00:00Commented Nov 11, 2021 at 6:56
-
\$\begingroup\$ This makes me want to learn convey. It looks awesome. \$\endgroup\$stanri– stanri2021年11月11日 18:33:18 +00:00Commented Nov 11, 2021 at 18:33
-
\$\begingroup\$ @MannyQueen, m90 thanks! Multiple outputs are well defined when they don't fire at the same step, so this is a very neat solution! \$\endgroup\$xash– xash2021年11月12日 18:21:18 +00:00Commented Nov 12, 2021 at 18:21
Rust v1.37.0, (削除) 59 (削除ここまで) (削除) 55 (削除ここまで) 47 bytes
|a:&[_]|(0..).zip(a).map(|i|a[i.0^1]).collect()
-2 bytes thanks to ZippyMagician
-2 bytes thanks to alephalpha
-8 bytes thanks to (0..).zip(a)
Rust is not a golfy language...
Port of the C# and JS answers
v1.37.0 is the version available on TIO
Rust stable, 54 bytes
|a:&[_]|a.chunks(2).flat_map(|a|[a[1],a[0]]).collect()
Thanks to ZippyMagician for this slightly golfier answer on the latest version of Rust.
-
1\$\begingroup\$ If you don’t use tio's outdated version of rust,
|a:&[i32]|a.chunks(2).flat_map(|a|[a[1],a[0]]).collect()is 3 bytes shorter \$\endgroup\$ZippyMagician– ZippyMagician2021年11月11日 01:22:00 +00:00Commented Nov 11, 2021 at 1:22 -
\$\begingroup\$ If you do, 57 bytes \$\endgroup\$ZippyMagician– ZippyMagician2021年11月11日 01:24:25 +00:00Commented Nov 11, 2021 at 1:24
-
1\$\begingroup\$ I think you can use
&[_]instead of&[i32]. \$\endgroup\$alephalpha– alephalpha2021年11月11日 01:36:31 +00:00Commented Nov 11, 2021 at 1:36 -
\$\begingroup\$ @ZippyMagician I managed to outgolf your stable rust answer with TIO's outdated version of rust :P \$\endgroup\$Mayube– Mayube2021年11月18日 17:44:38 +00:00Commented Nov 18, 2021 at 17:44
Python 2, 30 bytes
def f(a,b,*m):print b,a,;f(*m)
The function f takes input splatted like f(1,2,3,4,5,6), and prints the output space-separated, terminating with error.
34 bytes
lambda l:map(l.pop,len(l)/2*[1,0])
This works by alternating popping the elements at index 1 and index 0.
Wolfram Language (Mathematica), 22 bytes
0<##<1||#2&&#&�@##3&
Input [L...], and returns in an And. Works on integer inputs.
Wolfram Language (Mathematica), 24 bytes
{}=={##}||#2&&#&�@##3&
Input [L...], and returns in an And. Works on non-boolean inputs.
Wolfram Language (Mathematica), 26 bytes
#2~##&~#&@@@#~Partition~2&
Input [L], and returns a list. Works.
-
\$\begingroup\$
#~Partition~2~Reverse~2&is –2 bytes, if the OP doesn't mind the extra braces in the output:{1, 2, 3, 4, 5, 6}⟹{{2, 1}, {4, 3}, {6, 5}}\$\endgroup\$theorist– theorist2021年11月11日 05:39:10 +00:00Commented Nov 11, 2021 at 5:39 -
\$\begingroup\$ @theorist IMO, that doesn't output what the specs ask for - it outputs a list of pairs. \$\endgroup\$att– att2021年11月11日 06:50:16 +00:00Commented Nov 11, 2021 at 6:50
-
\$\begingroup\$ Yeah, figured you'd say that :). Could you save anything using
BlockMapinstead ofPartition? E.g.,BlockMap[Reverse,#,2]&is 2 bytes shorter than#~Partition~2~Reverse~2&. And how would you implement your function in the MMA front end? E.g.,list={1,2,3,4,5,6}#2~##&~#&@@@#~Partition~2&@listdoesn't work. \$\endgroup\$theorist– theorist2021年11月11日 07:30:31 +00:00Commented Nov 11, 2021 at 7:30 -
\$\begingroup\$ @theorist I initially thought about
BlockMap, but arguments to the function are provided as a list, so...@@#is required, makingPartitionwith@@@shorter. Use##&[#2,#]&instead; I'm not sure why infix##&is recognized in wolframscript but not in a notebook. \$\endgroup\$att– att2021年11月11日 07:36:00 +00:00Commented Nov 11, 2021 at 7:36
Python 3 + numpy, 31 bytes
lambda m:m[~-(m==m).cumsum()^1]
Expects a numpy array. Most of the code is about avoiding referencing numpy directly, so we can avoid the explicit import. It then calculates the indices directly by xoring a counter with 1.
-
\$\begingroup\$
(m*0).argsort()should work for -2. \$\endgroup\$ovs– ovs2021年11月13日 16:02:43 +00:00Commented Nov 13, 2021 at 16:02 -
1\$\begingroup\$ @ovs, only up to len(m)==16. From 17 numpy uses an unstable sort algorithm by default. tio.run/##DcoxDoAgDADAnVd0bB1MjIvxNwyADLRNwQE/… \$\endgroup\$loopy walt– loopy walt2021年11月13日 16:11:44 +00:00Commented Nov 13, 2021 at 16:11
Ly, 7 bytes
ir[foo]
Pretty straightforward, but might be worth posting since it's almost pronounceable. :)
ir -- read input codepoints into the stack, reverse the order
[ ] -- while the stack isn't empty
foo -- flip the top two entries and print as characters
Cubix, 14 bytes
[email protected]?i.o;o;.^
This is the first time I've tried to use Cubix, so I wouldn't be suprised if it's possible to do this with less code. It's a hard language to explain, since it's a 2D language where the code is wrapped around a cube. So the directions the instruction pointer take a hard to show in a description. I'll include a link to the online interpreter since it has a debug mode when you can see the way the code iterates through the cells.
But I'll try to explain it too...
[email protected]?i.o;o;.^ - code before it's wrapped on the cube...
i - (1) starts here, input a codepoint
? - branch if top of stack, <0 "left", >0 "right"
@ - "left" (true on EOF), halt program
^ - "right", set IP direction to "up"
? - same branch, but coming from another direction
i - "right", input another codepoint
o; - output top of stack as char, pop it off stack
o; - repeat... code wraps back to (1)
The . characters are no-ops and are needed to place the other characters in the right position so they will wrap into place on the cube.
Here's a link to the online interpreter http://ethproductions.github.io/cubix/?code=Li5ALmk/aS5vO287Ll4=&input=MTIzNDU2Nzg=&speed=20
AWK, (削除) 43 (削除ここまで) 41 bytes
{for(;++n<NF;n++)$n+=$(n+1)-($(n+1)=$n)}1
Thanks for Dominic van Essen for 2 less bytes!
{
for(;++n<NF;n++) Starts a loop though the numbers.
n has to start as 1, because 0ドル is the whole line.
$n+=$(n+1)-($(n+1)=$n) Swap the numbers two by two.
Readable: a += b - (b = a)
}
1 Prints the line.
-
1\$\begingroup\$ If you swap
++nforn=1(same bytes), it'll also work for subsequent lines of input... (currently the second 'try it online' line fails) \$\endgroup\$Dominic van Essen– Dominic van Essen2021年11月13日 18:22:58 +00:00Commented Nov 13, 2021 at 18:22 -
\$\begingroup\$ You are right!! Thanks for that. \$\endgroup\$Pedro Maimere– Pedro Maimere2021年11月13日 18:33:19 +00:00Commented Nov 13, 2021 at 18:33
-
1\$\begingroup\$ ...or 41 bytes if you don't care about subsequent lines (and I don't think you need to care about them here...) \$\endgroup\$Dominic van Essen– Dominic van Essen2021年11月13日 18:39:40 +00:00Commented Nov 13, 2021 at 18:39
C (clang), (削除) 53 (削除ここまで) \$\cdots\$ (削除) 43 (削除ここまで) 42 bytes
f(*l,n){*l^=l[1]^(l[1]=*l);n&&f(l+2,n-2);}
Inputs a pointer in an int array and the array's length (since pointers in C carry no length info).
Swaps every two elements in place.
Python 3.8 (pre-release), 35 bytes
def f(m):*m[1:],_,m[::2]=*m,m[1::2]
In-place. Essentially a golfed version of m[1::2],m[::2]=m[::2],m[1::2]
-
1\$\begingroup\$ Is there something special about the 3.8 prerelease? \$\endgroup\$Chris Bouchard– Chris Bouchard2021年11月11日 01:17:49 +00:00Commented Nov 11, 2021 at 1:17
-
\$\begingroup\$ @ChrisBouchard it just happens to be the latest version available on tio. The walrss operator can be useful for glfing. \$\endgroup\$loopy walt– loopy walt2021年11月11日 04:17:46 +00:00Commented Nov 11, 2021 at 4:17
-
\$\begingroup\$ I guess TIO just hasn't updated their python in a while? 3.8 was fully released Oct 2019, 3.9 is the most recent full release, and 3.10 is the current pre-release. \$\endgroup\$Gavin S. Yancey– Gavin S. Yancey2021年11月11日 20:06:14 +00:00Commented Nov 11, 2021 at 20:06
-
3\$\begingroup\$ As input is guaranteed to be of length at least 2, you can omit the
!. \$\endgroup\$pajonk– pajonk2021年11月11日 18:18:31 +00:00Commented Nov 11, 2021 at 18:18
4, 22 bytes
3.72082072152152072094
Readable + explanation:
3. 720 820 721 521 520 720 9 4
^^------------------------------ mandatory prefix
^^^-------------------------- initial input in cell 20
^^^-----------------^---- loop while cell 20 is nonzero
^^^------------------ input to cell 21
^^^-------------- output cell 21
^^^---------- output cell 20
^^^------ input to cell 20
^---- end loop
^-- exit
Corresponding Quartic program:
decl a, b
input a
loop a
input b
print b
print a
input a
end
CLC-INTERCAL, (削除) 95 (削除ここまで) 67 bytes.
Why does CLC-INTERCAL 1.-94.-2 lack !1~.1'? I could have golfed off one byte.
DOCOMEFROM#9(1)DOWRITEIN.1+.2DDOCOMEFROM'.1~.1'~#1(9)DOREADOUT.2+.1
Copy and paste to try it online!
Usage
- Each item of list must be in
ONEtoSIX FIVE FIVE THREE FIVE(inclusive);ZEROfor end of list.- Given from STDIN, delimited with a LF.
- Outputs to STDOUT, as roman number.
Try these inputs
ONE
TWO
ONE
TWO
ZERO
ONE
TWO
THREE
FOUR
FIVE
SIX
ZERO
Desmos, (削除) 39 (削除ここまで) 38 bytes
l=[1...L.length]
f(L)=L[l-1+2mod(l,2)]
BQN, (削除) 10 (削除ここまで) 9 bytesSBCS
-1 byte thanks to Razetime!
⥊·⌽ ̆∘‿2⊸⥊
∘‿2⥊x Reshape the input into a matrix with 2 columns and and the necessary number of rows.
⌽ ̆ Reverse horizontally (Swap the 2 columns).
⥊ Flatten into a vector.
An alternative using the Under operator at 10 bytes:
⌽ ̆⌾(∘‿2⊸⥊)
-
1\$\begingroup\$ useful userscript: github.com/razetime/userscripts/blob/main/bqncgcc.user.js \$\endgroup\$Razetime– Razetime2021年12月10日 10:10:52 +00:00Commented Dec 10, 2021 at 10:10
-
1\$\begingroup\$ @Rezetime thanks and thanks! I already read that Nothing is supposed to be useful in trains, now I see why \$\endgroup\$ovs– ovs2021年12月10日 10:28:28 +00:00Commented Dec 10, 2021 at 10:28
-
\$\begingroup\$ TIL about using
∘with Reshape, fascinating. \$\endgroup\$DLosc– DLosc2022年07月14日 17:30:18 +00:00Commented Jul 14, 2022 at 17:30
sed -n, 10 bytes
2~2{G;p};h
2~2{G;p}For even numbered lines, append hold space into pattern space and printhFor all lines, replace hold space with pattern space. This means that the hold space will always contain the previous, odd-numbered line when we are on an even-numbered line.
-
\$\begingroup\$ Can you get 10 bytes without
-n? \$\endgroup\$user41805– user418052023年01月06日 18:22:35 +00:00Commented Jan 6, 2023 at 18:22
-
\$\begingroup\$ Almost identical in sed \$\endgroup\$Digital Trauma– Digital Trauma2021年11月10日 17:07:19 +00:00Commented Nov 10, 2021 at 17:07
-
\$\begingroup\$ Very similar in Retina \$\endgroup\$Neil– Neil2021年11月10日 17:49:49 +00:00Commented Nov 10, 2021 at 17:49
-
\$\begingroup\$ Similar solution in Pip, though it's not the shortest Pip solution \$\endgroup\$DLosc– DLosc2021年11月10日 18:56:12 +00:00Commented Nov 10, 2021 at 18:56
C# (.NET Core) with Linq, (削除) 32 (削除ここまで) 26 bytes
a=>a.Select((n,i)=>a[i^1])
-8 bytes thanks to m90's witchcraft
C# (.NET Core), 73 bytes
a=>{for(int i=0,d=0;i<a.Length;i++){d=a[i];a[i]=a[++i];a[i]=d;}return a;}
char[]array in a language like C? If so, there is a certain built-in that would make the answer very short (s***). \$\endgroup\$