# Swap every two elements in a list

## 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

• 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 Nov 10, 2021 at 16:42
• 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? Nov 10, 2021 at 17:36
• Yes, that's fine Nov 10, 2021 at 20:19
• 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***). Nov 11, 2021 at 0:29
• 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). Nov 12, 2021 at 0:41

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

# 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.

# Japt, 4 bytes

ò mé

Try it

ò      - chunks of 2
mé   - rotate each
• This outputs a 2d list, you can use c instead of m to fix it Feb 14 at 13:16
• @noodle man Theoretically it does return a 2d list but in practice you need the Q flag to output it by implicit output, your suggestion to use c' method instead of m' is correct though Feb 14 at 20:54
• Yeah, I know, I was just in the mood for making pointless corrections :) Feb 14 at 22:10

# 05AB1E, 4 bytes

2ôí˜

4 bytes alternatives:

ιRø˜
2ô€

Explanation:

2ô   # Split the (implicit) input-list into parts of size 2
#  i.e. [1,2,3,4,5,6] → [[1,2],[3,4],[5,6]]
í  # Reverse each pair
#  → [[2,1],[4,3],[6,5]]
˜ # Flatten the list of pairs
#  → [2,1,4,3,6,5]
# (after which this list is output implicitly as result)

ι    # Uninterleave the (implicit) input-list, using 2 as implicit second argument
#  i.e. [1,2,3,4,5,6] → [[1,3,5],[2,4,6]]
R   # Reverse it
#  → [[2,4,6],[1,3,5]]
ø  # Zip/transpose, swapping rows/columns
#  → [[2,1],[4,3],[6,5]]
˜ # Flatten the list of pairs
#  → [2,1,4,3,6,5]
# (after which this list is output implicitly as result)

2ô   # Split the (implicit) input-list into parts of size 2
#  i.e. [1,2,3,4,5,6] → [[1,2],[3,4],[5,6]]
€  # Map over each pair:
#  Pop and push the pair to the stack
# (€ is usually used to flatten a multi-level list one level down. One side-effect
# is that the items are dumped in reversed order, which is what we want in this
# case)
#  → [2,1,4,3,6,5]
# (after which this list is output implicitly as result)

# Pure Bash, 32 + 1 = 33 bytes

One additional byte for filename specification: x.

echo "$2$1"
shift 2

# Grok, 11 bytes

:Y}:zpz
q

Try it Online!

Explanation:

:Y      # Get input and copy it to the register
}     # Quit if no more input
q
:z   # Print next input
pz # Print value in the register

,_2,/

# Explained

_2 … /    pairwise reduce
,`     By reverse concatenation
,         Ravel

# PowerShell, 31 bytes

%{If(++$i%2){$j=$_}Else{$_,$j}} Input comes from the pipeline. Try it online! Try it in a PS console:$array = 1,2,3,4,5,6
$result =$array |
%{If(++$i%2){$j=$_}Else{$_,$j}} "$($array -join ',') -->$($result -join ',')" ## Explanation % is an Alias for the Cmdlet "ForEach-Object", which accepts input from the pipeline and processes each incoming object inside the ScriptBlock {...} If(++$i%2) first increments $i (which starts at 0) in each loop and takes it modulo 2 If the result is 1: {$j=$_} the current element will be saved in in$j
Otherwise (0):
{$_,$j} first puts the current element, then the element from the last loop iteration into the pipeline/stdout.

L,2$T€bRbF Try it online! Uses Add++'s much more powerful functional mode, rather than it's vanilla mode. However, definitely check out the other Add++ answer, as it doesn't use any form of indexing, just looping! ## How it works L,2$T€bRbF - Unnamed lambda function. Takes 1 argument, L
L,         - Define the lambda:
2$T - Split into runs of length 2 € - Over each: bR - Reverse it bF - Flatten and return # CJam, 10 bytes N{riripp}h Try it online! ### Explanation N e# Push newline (this is truthy) { }h e# Do while without popping the condition: infinite loop r e# Read line and push string to the stack i e# Interpret as integer r e# Read line and push string to the stack i e# Interpret as integer p e# Pop and print with a newline p e# Pop and print with a newline e# Implicitly print stack: newline # Pxem, 18 + 0 = 18 bytes. The configure is: • No breaking loop when insufficient items. • Abort to illegal integer input. Filename: .w._._.n .o.n .o.a Content is empty. Try it online! ## Usage • With STDIN and STDOUT. • Each integer shall be given, separated by one or more space characters. • Outputted separated with a space. # Coconut, 48 bytes l->(l[1::2],l[:-1:2])|*>zip|>reduce$(+)

Try it online!

Python equivalent:

from functools import reduce
f = lambda l: reduce(add, zip(l[1::2], l[:-1:2]))

# Burlesque, 6 bytes

2co)^p

Try it online!

Improved: Remembered map shorthand

2co   # Chunks of 2
)^p   # Push in reverse for each block

# Burlesque, 7 bytes

2co{}^m

Try it online!

2co   # Chunks of 2
{}^m  # Push in reverse for each block (strictly push-map with a nop)

# C++ (gcc), 50 bytes

[](auto&v){for(int&i:v)swap(i,(&i)[int(&i)%8<1]);}

-5 bytes thanks to ceilingcat!

Try it online!

# Pari/GP, 27 bytes

l->[l[i-(-1)^i]|i<-[1..#l]]

Try it online!

# Husk, 4 bytes

ṁ↔C2

Try it online!

### Explanation

ṁ↔C2
C2  slices of length 2
ṁ↔    flatmap reverse

# x86-16 machine code, 8 7 bytes

00000000: aca4 aa49 e2fa c3                        ...I...

Listing:

TWO_LOOP:
AC      LODSB               ; load first byte (into AL)
A4      MOVSB               ; move second byte into first byte
AA      STOSB               ; store first byte (from AL) into second byte
49      DEC  CX             ; only loop half as many times as length
E2 F9   LOOP TWO_LOOP
C3      RET

Callable function: input list at [SI], output to [DI] length in CX.

-1 bytes thx to @m90!

• Improvement: lodsb; movsb; stosb
– m90
Jul 13, 2022 at 6:46
• @m90 ooh that's nice! Thx! Jul 14, 2022 at 13:26

# Brachylog, 5 bytes

ġ₂↔ᵐc

Try it online!

### Explanation

ġ₂         Split the list in groups of 2 consecutive elements
↔ᵐ       Map reverse
c      Concatenate