22
\$\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
  • 4
    \$\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 '21 at 16:42
  • 4
    \$\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 '21 at 17:36
  • \$\begingroup\$ Yes, that's fine \$\endgroup\$
    – matusf
    Nov 10 '21 at 20:19
  • 3
    \$\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 '21 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 '21 at 0:41

61 Answers 61

18
\$\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 '21 at 8:36
  • \$\begingroup\$ @wasif Oh well, still beats Jelly and osabie. \$\endgroup\$
    – emanresu A
    Nov 11 '21 at 9:14
11
\$\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 '21 at 6:56
  • \$\begingroup\$ This makes me want to learn convey. It looks awesome. \$\endgroup\$
    – stanri
    Nov 11 '21 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 '21 at 18:21
10
\$\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\$
10
\$\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 '21 at 17:49
  • 2
    \$\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 '21 at 17:53
10
\$\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 '21 at 21:13
  • 2
    \$\begingroup\$ @Roman Czyborra nice but there's nothing stopping iterate.. that way works fine \$\endgroup\$
    – AZTECCO
    Nov 23 '21 at 0:06
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 '21 at 1:22
  • \$\begingroup\$ If you do, 57 bytes \$\endgroup\$ Nov 11 '21 at 1:24
  • 1
    \$\begingroup\$ I think you can use &[_] instead of &[i32]. \$\endgroup\$
    – alephalpha
    Nov 11 '21 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 '21 at 17:44
9
\$\begingroup\$

brainfuck, 9 bytes

,[>,.<.,]

Try it online!

\$\endgroup\$
6
\$\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\$
6
\$\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 '21 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 '21 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 '21 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 '21 at 7:36
5
\$\begingroup\$

Python 3, 36 bytes

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

Try it online!

\$\endgroup\$
5
\$\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\$
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 '21 at 18:51
  • \$\begingroup\$ @att I know, what's the problem? \$\endgroup\$
    – Noodle9
    Nov 10 '21 at 18:57
4
\$\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
4
\$\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

..@.i?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...

..@.i?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\$

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 '21 at 18:22
  • \$\begingroup\$ You are right!! Thanks for that. \$\endgroup\$ Nov 13 '21 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 '21 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\$
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\$
1
  • 1
    \$\begingroup\$ Excellent solution. Didn't realise there was already a Zsh answer - puts my 30B to shame :P \$\endgroup\$
    – roblogic
    Nov 12 '21 at 9:53
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\$
3
\$\begingroup\$

Rockstar, 98 bytes

Listen to B
cut B with ","
I is 0
while I is less than B
shout B at I+1
shout B at I
Build I up up

Try it online!
(Must manually copy-paste code)

Takes input as comma-separated string of numbers eg:

1,2,3,4,5,6

Outputs as newline-separated string of numbers eg:

2
1
4
3
6
5

Rockstar has no modulo, and no bitwise operators, so porting the other solutions is out of the question.

Explanation

Listen to B             ; Read input to B
cut B with ","          ; Split B on ","
I is 0                  ; Set I to 0
while I is less than B  ; While I < B.length
                        ; (Rockstar Arrays automatically coerce to length when used as a scalar)
shout B at I+1          ; Print B[I+1] with trailing newline
shout B at I            ; Print B[I] with trailing newline
Build I up up           ; Increment I twice (each 'up' increments)
\$\endgroup\$
3
\$\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 '21 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 '21 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 '21 at 20:06
3
\$\begingroup\$

Raku, 19 17 bytes

*.flatmap:{$^b,$^a}

*[^* »+»<1 -1>]

Try it online!

  • *[...] is an anonymous function that slices into the list given as the sole argument using the bracketed expression, which is another anonymous function.
  • ^* »+» <1 -1> takes the numbers from 0 up to one less than the argument, and produces a new list by alternatively adding 1 and -1. Those reordered indices are used to slice into the original input array.
\$\endgroup\$
3
\$\begingroup\$

R, 29 bytes

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

Try it online!

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

Ruby, 26 bytes

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

Try it online!

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

Whitespace, 65 bytes

[N
S S N
_Create_Label_LOOP][S S S N
_Push_0][S N
S _Duplicate_0][T   N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve_input1][S N
S _Duplicate_input1][S N
S _Duplicate_input1][T  N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve_input2][T N
S T _Print_input2_as_integer][S S S T   S T S N
_Push_10][S N
S _Duplicate_10][T  N
S S _Print_10_as_character][S N
T   _Swap_top_two][T    N
S T _Print_input1_as_integer][T N
S S _Print_10_as_character][N
S N
N
_Jump_to_Label_LOOP]

Letters S (space), T (tab), and N (new-line) added as highlighting only.
[..._some_action] added as explanation only.

Whitespace doesn't have lists, so I/O are newline delimited (strictly non-negative) integers.

Try it online (with raw spaces, tabs and new-lines only).

Explanation in pseudo-code:

LOOP:
  Integer a = STDIN as integer
  Integer b = STDIN as integer
  Print b as integer to STDOUT
  Print '\n' as character to STDOUT
  Print a as integer to STDOUT
  Print '\n' as character to STDOUT
  Go to next iteration of LOOP

This will stop with an error automatically when there are no more inputs.

: For every second input it will use the input before it as heap-address ([SNS_Duplicate_input1][SNS_Duplicate_input1][TNTT_Read_STDIN_as_integer]), so the inputs should be strictly non-negative, since negative heap addresses aren't allowed in Whitespace.

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

J, 9 bytes

[:,_2|.\]

Try it online!

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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