33
\$\begingroup\$

Challenge

Let's have a list L of n elements. The task is to swap every two elements in this list.

Constraints

  • The list L has at least two elements
  • Size of the list L is 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

asked Nov 10, 2021 at 16:38
\$\endgroup\$
5
  • 5
    \$\begingroup\$ Welcome to Code Golf and nice first question! For future reference, we recommend using the Sandbox to get feedback on challenge ideas before posting them to main \$\endgroup\$ Commented Nov 10, 2021 at 16:42
  • 5
    \$\begingroup\$ What types of elements must the list support? In particular, is it all right if a solution only works on lists of non-negative/unsigned integers? \$\endgroup\$ Commented Nov 10, 2021 at 17:36
  • \$\begingroup\$ Yes, that's fine \$\endgroup\$ Commented Nov 10, 2021 at 20:19
  • 4
    \$\begingroup\$ Can we use 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\$ Commented Nov 11, 2021 at 0:29
  • \$\begingroup\$ Sure, go ahead. However, I'd say that if there are two solutions with the same length, then the more general one wins (the one that works for more inputs/datatypes). \$\endgroup\$ Commented Nov 12, 2021 at 0:41

92 Answers 92

1
2 3 4
22
\$\begingroup\$

><>, (削除) 4 (削除ここまで) 3 bytes

i#o

Try it online!

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.
answered Nov 10, 2021 at 19:12
\$\endgroup\$
2
  • \$\begingroup\$ no longer beats Vyxal \$\endgroup\$ Commented Nov 11, 2021 at 8:36
  • \$\begingroup\$ @wasif Oh well, still beats Jelly and osabie. \$\endgroup\$ Commented Nov 11, 2021 at 9:14
14
\$\begingroup\$

Python 3, 34 bytes

f=lambda l:l and l[1::-1]+f(l[2:])

Try it online!

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.

answered Nov 10, 2021 at 17:13
\$\endgroup\$
13
\$\begingroup\$

Vyxal r, 2 bytes

yY

Try it Online!

Explanation:

y # Uninterleave
 Y # Interleave
answered Nov 10, 2021 at 17:48
\$\endgroup\$
2
  • 1
    \$\begingroup\$ What does the r flag do? \$\endgroup\$ Commented Nov 10, 2021 at 17:49
  • 3
    \$\begingroup\$ @ZippyMagician The r flag makes all commands take their arguments in reverse order. That doesn't affect y since it only has one argument, but it does affect Y, meaning that the program is essentially equivalent to y$Y, which swaps the halves before interleaving. \$\endgroup\$ Commented Nov 10, 2021 at 17:53
13
\$\begingroup\$

Haskell, 22 bytes

f(a:b:c)=b:a:f c
f x=x

Try it online!

answered Nov 10, 2021 at 23:37
\$\endgroup\$
2
  • \$\begingroup\$ f=concatMap(reverse.take 2).iterate(drop 2) \$\endgroup\$ Commented Nov 22, 2021 at 21:13
  • 2
    \$\begingroup\$ @Roman Czyborra nice but there's nothing stopping iterate.. that way works fine \$\endgroup\$ Commented Nov 23, 2021 at 0:06
12
\$\begingroup\$

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

Try it online!

{ 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^

Try it online!

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.

variant 2 with input 1 to 6

answered Nov 10, 2021 at 17:45
\$\endgroup\$
3
  • \$\begingroup\$ The second one can be made shorter with some rearrangement. \$\endgroup\$ Commented Nov 11, 2021 at 6:56
  • \$\begingroup\$ This makes me want to learn convey. It looks awesome. \$\endgroup\$ Commented 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\$ Commented Nov 12, 2021 at 18:21
11
\$\begingroup\$

brainfuck, 9 bytes

,[>,.<.,]

Try it online!

answered Nov 11, 2021 at 0:11
\$\endgroup\$
10
\$\begingroup\$

Rust v1.37.0, (削除) 59 (削除ここまで) (削除) 55 (削除ここまで) 47 bytes

|a:&[_]|(0..).zip(a).map(|i|a[i.0^1]).collect()

Try it online!

-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()

Try it online!

Thanks to ZippyMagician for this slightly golfier answer on the latest version of Rust.

answered Nov 10, 2021 at 18:17
\$\endgroup\$
4
  • 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\$ Commented Nov 11, 2021 at 1:22
  • \$\begingroup\$ If you do, 57 bytes \$\endgroup\$ Commented Nov 11, 2021 at 1:24
  • 1
    \$\begingroup\$ I think you can use &[_] instead of &[i32]. \$\endgroup\$ Commented 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\$ Commented Nov 18, 2021 at 17:44
9
\$\begingroup\$

Python 2, 30 bytes

def f(a,b,*m):print b,a,;f(*m)

Try it online!

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

Try it online!

This works by alternating popping the elements at index 1 and index 0.

answered Nov 11, 2021 at 7:47
\$\endgroup\$
7
\$\begingroup\$

Wolfram Language (Mathematica), 22 bytes

0<##<1||#2&&#&&#0@##3&

Try it online!

Input [L...], and returns in an And. Works on integer inputs.


Wolfram Language (Mathematica), 24 bytes

{}=={##}||#2&&#&&#0@##3&

Try it online!

Input [L...], and returns in an And. Works on non-boolean inputs.

Wolfram Language (Mathematica), 26 bytes

#2~##&~#&@@@#~Partition~2&

Try it online!

Input [L], and returns a list. Works.

answered Nov 10, 2021 at 18:36
\$\endgroup\$
4
  • \$\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\$ Commented 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\$ Commented Nov 11, 2021 at 6:50
  • \$\begingroup\$ Yeah, figured you'd say that :). Could you save anything using BlockMap instead of Partition? 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&@list doesn't work. \$\endgroup\$ Commented 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, making Partition with @@@ shorter. Use ##&[#2,#]& instead; I'm not sure why infix ##& is recognized in wolframscript but not in a notebook. \$\endgroup\$ Commented Nov 11, 2021 at 7:36
6
\$\begingroup\$

JavaScript (ES6), 23 bytes

x=>x.map((_,i)=>x[i^1])

The [i^1] is thanks to m90 in TNB

Try it online!

answered Nov 10, 2021 at 17:54
\$\endgroup\$
5
\$\begingroup\$

Python 3, 36 bytes

lambda a:sum(zip(a[1::2],a[::2]),())

Try it online!

answered Nov 10, 2021 at 16:47
\$\endgroup\$
5
\$\begingroup\$

Python 3 + numpy, 31 bytes

lambda m:m[~-(m==m).cumsum()^1]

Try it online!

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.

answered Nov 11, 2021 at 0:17
\$\endgroup\$
2
  • \$\begingroup\$ (m*0).argsort() should work for -2. \$\endgroup\$ Commented 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\$ Commented Nov 13, 2021 at 16:11
5
\$\begingroup\$

Ly, 7 bytes

ir[foo]

Try it online!

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;.^

Try it online!

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

answered Nov 11, 2021 at 1:43
\$\endgroup\$
5
\$\begingroup\$

AWK, (削除) 43 (削除ここまで) 41 bytes

{for(;++n<NF;n++)$n+=$(n+1)-($(n+1)=$n)}1

Thanks for Dominic van Essen for 2 less bytes!

Try it online!

{
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.
answered Nov 12, 2021 at 23:57
\$\endgroup\$
3
  • 1
    \$\begingroup\$ If you swap ++n for n=1 (same bytes), it'll also work for subsequent lines of input... (currently the second 'try it online' line fails) \$\endgroup\$ Commented Nov 13, 2021 at 18:22
  • \$\begingroup\$ You are right!! Thanks for that. \$\endgroup\$ Commented 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\$ Commented Nov 13, 2021 at 18:39
4
\$\begingroup\$

C (clang), (削除) 53 (削除ここまで) \$\cdots\$ (削除) 43 (削除ここまで) 42 bytes

f(*l,n){*l^=l[1]^(l[1]=*l);n&&f(l+2,n-2);}

Try it online!

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.

answered Nov 10, 2021 at 17:13
\$\endgroup\$
2
  • 1
    \$\begingroup\$ this also modifies past the end of the array \$\endgroup\$ Commented Nov 10, 2021 at 18:51
  • 1
    \$\begingroup\$ @att I know, what's the problem? \$\endgroup\$ Commented Nov 10, 2021 at 18:57
4
\$\begingroup\$

Python 3.8 (pre-release), 35 bytes

def f(m):*m[1:],_,m[::2]=*m,m[1::2]

Try it online!

In-place. Essentially a golfed version of m[1::2],m[::2]=m[::2],m[1::2]

answered Nov 10, 2021 at 23:16
\$\endgroup\$
3
  • 1
    \$\begingroup\$ Is there something special about the 3.8 prerelease? \$\endgroup\$ Commented 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\$ Commented 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\$ Commented Nov 11, 2021 at 20:06
4
\$\begingroup\$

R, 29 bytes

function(l)l[seq(!l)+2*1:0-1]

Try it online!

answered Nov 11, 2021 at 2:16
\$\endgroup\$
1
  • 3
    \$\begingroup\$ As input is guaranteed to be of length at least 2, you can omit the !. \$\endgroup\$ Commented Nov 11, 2021 at 18:18
4
\$\begingroup\$

Ruby, 26 bytes

->l{r=-1;l.map{l[1^r+=1]}}

Try it online!

answered Nov 11, 2021 at 7:49
\$\endgroup\$
4
\$\begingroup\$

J, 9 bytes

[:,_2|.\]

Try it online!

answered Nov 12, 2021 at 7:51
\$\endgroup\$
4
\$\begingroup\$

4, 22 bytes

3.72082072152152072094

Try it online!

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
answered Nov 12, 2021 at 22:52
\$\endgroup\$
4
\$\begingroup\$

T-SQL, 32 bytes

Input is a table variable

SELECT a FROM @ ORDER BY b+b%2*2

Try it online

answered Nov 12, 2021 at 13:53
\$\endgroup\$
4
\$\begingroup\$

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 ONE to SIX FIVE FIVE THREE FIVE (inclusive); ZERO for 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
answered Nov 13, 2021 at 15:41
\$\endgroup\$
4
\$\begingroup\$

Desmos, (削除) 39 (削除ここまで) 38 bytes

l=[1...L.length]
f(L)=L[l-1+2mod(l,2)]

Try It On Desmos!

Try It On Desmos! - Prettified

answered Nov 11, 2021 at 6:53
\$\endgroup\$
0
4
\$\begingroup\$

BQN, (削除) 10 (削除ここまで) 9 bytesSBCS

-1 byte thanks to Razetime!

⥊·⌽ ̆∘‿2⊸⥊

Run online!

∘‿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⊸⥊)

Try it online!

answered Dec 9, 2021 at 15:50
\$\endgroup\$
3
  • 1
    \$\begingroup\$ useful userscript: github.com/razetime/userscripts/blob/main/bqncgcc.user.js \$\endgroup\$ Commented 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\$ Commented Dec 10, 2021 at 10:28
  • \$\begingroup\$ TIL about using with Reshape, fascinating. \$\endgroup\$ Commented Jul 14, 2022 at 17:30
4
\$\begingroup\$

sed -n, 10 bytes

2~2{G;p};h

Try it online!

  • 2~2{G;p} For even numbered lines, append hold space into pattern space and print
  • h For 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.
answered Jul 17, 2022 at 13:32
\$\endgroup\$
1
  • \$\begingroup\$ Can you get 10 bytes without -n? \$\endgroup\$ Commented Jan 6, 2023 at 18:22
3
\$\begingroup\$

Jelly, 4 bytes

s2UF

Try It Online!

s2 Slices of length 2
 U Reverse each
 F Flatten
answered Nov 10, 2021 at 16:41
\$\endgroup\$
3
\$\begingroup\$

Perl 5 -p, 21 bytes

s/(\S+) (\S+)/2ドル 1ドル/g

Try it online!

answered Nov 10, 2021 at 16:46
\$\endgroup\$
3
  • \$\begingroup\$ Almost identical in sed \$\endgroup\$ Commented Nov 10, 2021 at 17:07
  • \$\begingroup\$ Very similar in Retina \$\endgroup\$ Commented Nov 10, 2021 at 17:49
  • \$\begingroup\$ Similar solution in Pip, though it's not the shortest Pip solution \$\endgroup\$ Commented Nov 10, 2021 at 18:56
3
\$\begingroup\$

APL+WIN, 17 bytes

Prompts for vector

,⌽((×ばつ⍴r),2)⍴r←⎕

Try it online! Thanks to Dyalog Classic

answered Nov 10, 2021 at 17:29
\$\endgroup\$
3
\$\begingroup\$

Zsh, 18 bytes

for a b;<<<$b<<<$a

Attempt This Online!

answered Nov 10, 2021 at 17:36
\$\endgroup\$
0
3
\$\begingroup\$

C# (.NET Core) with Linq, (削除) 32 (削除ここまで) 26 bytes

a=>a.Select((n,i)=>a[i^1])

Try it online!

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

Try it online!

answered Nov 10, 2021 at 17:34
\$\endgroup\$
1
2 3 4

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.