30
\$\begingroup\$

Challenge

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

Constrains

  • 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

\$\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\$
    – Mayube
    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\$
    – DLosc
    Nov 10, 2021 at 17:36
  • \$\begingroup\$ Yes, that's fine \$\endgroup\$
    – matusf
    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\$ 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\$
    – matusf
    Nov 12, 2021 at 0:41

83 Answers 83

21
\$\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.
\$\endgroup\$
2
  • \$\begingroup\$ no longer beats Vyxal \$\endgroup\$
    – Wasif
    Nov 11, 2021 at 8:36
  • \$\begingroup\$ @wasif Oh well, still beats Jelly and osabie. \$\endgroup\$
    – emanresu A
    Nov 11, 2021 at 9:14
13
\$\begingroup\$

Vyxal r, 2 bytes

yY

Try it Online!

Explanation:

y  # Uninterleave
 Y # Interleave
\$\endgroup\$
2
  • 1
    \$\begingroup\$ What does the r flag do? \$\endgroup\$ 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\$ Nov 10, 2021 at 17:53
12
\$\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.

\$\endgroup\$
12
\$\begingroup\$

Haskell, 22 bytes

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

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ f=concatMap(reverse.take 2).iterate(drop 2) \$\endgroup\$ Nov 22, 2021 at 21:13
  • 2
    \$\begingroup\$ @Roman Czyborra nice but there's nothing stopping iterate.. that way works fine \$\endgroup\$
    – AZTECCO
    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

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

brainfuck, 9 bytes

,[>,.<.,]

Try it online!

\$\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.

\$\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\$ Nov 11, 2021 at 1:22
  • \$\begingroup\$ If you do, 57 bytes \$\endgroup\$ Nov 11, 2021 at 1:24
  • 1
    \$\begingroup\$ I think you can use &[_] instead of &[i32]. \$\endgroup\$
    – alephalpha
    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
    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.

\$\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.

\$\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\$
    – theorist
    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
    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\$
    – theorist
    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\$
    – att
    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!

\$\endgroup\$
5
\$\begingroup\$

Python 3, 36 bytes

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

Try it online!

\$\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.

\$\endgroup\$
2
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

\$\endgroup\$
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.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ this also modifies past the end of the array \$\endgroup\$
    – att
    Nov 10, 2021 at 18:51
  • 1
    \$\begingroup\$ @att I know, what's the problem? \$\endgroup\$
    – Noodle9
    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]

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

R, 29 bytes

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

Try it online!

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

Ruby, 26 bytes

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

Try it online!

\$\endgroup\$
4
\$\begingroup\$

J, 9 bytes

[:,_2|.\]

Try it online!

\$\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
\$\endgroup\$
4
\$\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.
\$\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\$ Nov 13, 2021 at 18:22
  • \$\begingroup\$ You are right!! Thanks for that. \$\endgroup\$ 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\$ Nov 13, 2021 at 18:39
4
\$\begingroup\$

T-SQL, 32 bytes

Input is a table variable

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

Try it online

\$\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
\$\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

\$\endgroup\$
0
4
\$\begingroup\$

BQN, 10 9 bytesSBCS

-1 byte thanks to Razetime!

⥊·⌽˘∘‿2⊸⥊

Run online!

∘‿2⥊𝕩 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!

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

Jelly, 4 bytes

s2UF

Try It Online!

s2    Slices of length 2
  U   Reverse each
   F  Flatten
\$\endgroup\$
3
\$\begingroup\$

Perl 5 -p, 21 bytes

s/(\S+) (\S+)/$2 $1/g

Try it online!

\$\endgroup\$
3
3
\$\begingroup\$

APL+WIN, 17 bytes

Prompts for vector

,⌽((.5×⍴r),2)⍴r←⎕

Try it online! Thanks to Dyalog Classic

\$\endgroup\$
3
\$\begingroup\$

Zsh, 18 bytes

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

Attempt This Online!

\$\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!

\$\endgroup\$
3
\$\begingroup\$

Add++, 57 bytes

a:?
b:0
n:0
m:3
`b
Ea,Ib=n,,b:1,,x:i,+1,Ib=m,,b:0,,Oi,,Ox

Try it online!

Input is the first argument.

\$\endgroup\$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.