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

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

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

Japt, 4 bytes

ò mé

Try it

ò      - chunks of 2
  mé   - rotate each
\$\endgroup\$
3
  • \$\begingroup\$ This outputs a 2d list, you can use c instead of m to fix it \$\endgroup\$
    – noodle man
    Feb 14 at 13:16
  • \$\begingroup\$ @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 \$\endgroup\$
    – AZTECCO
    Feb 14 at 20:54
  • 1
    \$\begingroup\$ Yeah, I know, I was just in the mood for making pointless corrections :) \$\endgroup\$
    – noodle man
    Feb 14 at 22:10
3
\$\begingroup\$

05AB1E, 4 bytes

2ôí˜

Try it online or verify all test cases.

4 bytes alternatives:

ιRø˜

Try it online or verify all test cases.

2ô€`

Try it online or verify all test cases.

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)
\$\endgroup\$
3
\$\begingroup\$

Pure Bash, 32 + 1 = 33 bytes

One additional byte for filename specification: x.

echo "$2
$1"
shift 2
(($#))&&. x

Try it online!

Usage

  • Input from program arguments.
  • Outputs to stdout.

Pure Bash, 34 + 1 = 35 bytes

One additional byte for filename specification: x.

read x
read y||>x
echo "$y
$x"
. x

Try it online!

Usage

  • Each item is given from STDIN.
  • Outputs to STDOUT.
  • Items are separated by a LF.
\$\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\$

Red, 37 bytes

func[a][foreach[b c]a[print[c lf b]]]

Try it online!

Alternative

Much longer but more fun approach using parse:

Red, 59 bytes

func[a][parse a[collect[any[b: skip keep skip keep(b/1)]]]]

Try it online!

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

Python 2, 49 39 bytes

lambda l:[l[c^1]for c in range(len(l))]

Try it online!

-10 with thanks to @MannyQueen for an awesome tip.

Simply because no-one has submitted a Python 2 answer yet.

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

Vim, 11 bytes

qqddpj@qq@q

Try it online!

Explanation:

qq    @qq@q # Loop:
  dd        #  Delete the line
    p       #  Paste it below the next line
     j      #  Move down a line
\$\endgroup\$
3
\$\begingroup\$

Factor + sequences.merged, 34 29 bytes

[ 2 group unzip swap 2merge ]

Try it online!

Explanation

        ! { 1 2 3 4 5 6 }
2 group ! { { 1 2 } { 3 4 } { 5 6 } }
unzip   ! { 1 3 5 } { 2 4 6 }
swap    ! { 2 4 6 } { 1 3 5 }
2merge  ! { 2 1 4 3 6 5 }
\$\endgroup\$
3
\$\begingroup\$

APL, 15 bytes

{,⌽⍵⍴⍨(2÷⍨≢⍵)2}

The same idea as in the existing solution, but implemented as a separate function and two bytes less.

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

Nibbles, 3.5 3 bytes (6 nibbles)

\+\`/~
   `/      # chunks of input
     ~     # (using default size = 2),
  \        # reverse,
 +         # concatenate,
\          # and reverse again.

enter image description here

\$\endgroup\$
3
\$\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.
\$\endgroup\$
1
  • \$\begingroup\$ Can you get 10 bytes without -n? \$\endgroup\$
    – user41805
    Jan 6, 2023 at 18:22
3
\$\begingroup\$

Desmos, 42 38 bytes

-4 bytes thanks to @aiden's suggestion and wackscope variables

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

Try It On Desmos!

\$\endgroup\$
4
  • \$\begingroup\$ Nice answer! Though when you use a list comprehension like that, it is golfier to just move l to its own line like l=[1...L.length], and don't use a list comprehension entirely. See my answer to this question, for example. \$\endgroup\$
    – Aiden Chow
    Jul 18, 2022 at 2:32
  • \$\begingroup\$ Yeah we can move it to its own line but the question asked for a function and so when I have to move l to its own line I'll have to also account for l(L) which will consume more if not the same number of bytes \$\endgroup\$ Jul 18, 2022 at 2:51
  • \$\begingroup\$ @AidenChow wackscope variables did the trick! thanks \$\endgroup\$ Jul 18, 2022 at 2:58
  • \$\begingroup\$ @Steffan Ah right, I see that it worked for me because of some desmos extension I had and the space was to make sure it pasted 2*mod(l,2) instead of mod(2l,2). Anyways, how do I revert it back to the previous edit? Edit: found it 👍 \$\endgroup\$ Jul 20, 2022 at 21:51
3
\$\begingroup\$

Pip -xp, 5 8 7 bytes

R_MF<>a

Try It Online!

\$\endgroup\$
5
  • \$\begingroup\$ This solution works for strings, but since the challenge specifies lists, I'd say you need list I/O and a FL in front of the R. \$\endgroup\$
    – DLosc
    Mar 6, 2023 at 17:17
  • \$\begingroup\$ @DLosc does the list need to be flattened? It doesn't seem to be specified in the question... \$\endgroup\$
    – Baby_Boy
    Mar 6, 2023 at 17:22
  • 1
    \$\begingroup\$ The question is a tad underspecified, but in such cases I'd err on the side of what the OP probably intended: list of integers in, modified list of integers out. \$\endgroup\$
    – DLosc
    Mar 6, 2023 at 17:30
  • \$\begingroup\$ @DLosc Alright, love pip btw :) \$\endgroup\$
    – Baby_Boy
    Mar 6, 2023 at 17:34
  • 1
    \$\begingroup\$ Thanks! :D Actually, I just realized you can get it down to 7 bytes using map-flatten: R_MF<>a \$\endgroup\$
    – DLosc
    Mar 6, 2023 at 17:37
3
\$\begingroup\$

Rockstar, 63 bytes

Takes input as a space separated string, outputs each element on its own line. 9 bytes could be saved if we were guaranteed every element of the array was a single digit by taking input with no delimiting spaces.

listen to S
cut S with " "
while S
roll S in N
say roll S
say N

Try it (Code will need to be pasted in)

listen to S        :Read the input string into variable S
cut S with " "     :Split S to an array on spaces
while S            :While S is not empty
roll S in N        :  Pop the first element from S into variable N
say roll S         :  Pop the first element from S and output it
say N              :  Output N
\$\endgroup\$
2
\$\begingroup\$

Vyxal, 4 bytes

2ẇRf

Try it Online!

Explanation:

2ẇ   # Split list into groups of two
  R  # Reverse each group
   f # Flatten
\$\endgroup\$
2
  • \$\begingroup\$ In 2.6pre1 this is 3 bytes - ǒ splits into chunks of 2 \$\endgroup\$
    – emanresu A
    Nov 10, 2021 at 18:50
  • \$\begingroup\$ @emanresuA Oh, nice! I still have yet to check out the prerelease, I'll have to do that. You can also get three bytes in this version by using y$Y, which is just the flagless version of my flaggy answer. \$\endgroup\$ Nov 10, 2021 at 18:53
2
\$\begingroup\$

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

ayr, 6 bytes

,_2,`/

Explained

 _2 … /    pairwise reduce
    ,`     By reverse concatenation
,         Ravel
\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

Add++, 10 bytes

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

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

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

Coconut, 48 bytes

l->(l[1::2],l[:-1:2])|*>zip|>reduce$(+)

Try it online!

Python equivalent:

from functools import reduce
from operator import add
f = lambda l: reduce(add, zip(l[1::2], l[:-1:2]))
\$\endgroup\$
2
\$\begingroup\$

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

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!

\$\endgroup\$
0
2
\$\begingroup\$

Pari/GP, 27 bytes

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

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Husk, 4 bytes

ṁ↔C2

Try it online!

Explanation

ṁ↔C2
  C2  slices of length 2
ṁ↔    flatmap reverse
\$\endgroup\$
2
\$\begingroup\$

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!

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Improvement: lodsb; movsb; stosb \$\endgroup\$
    – m90
    Jul 13, 2022 at 6:46
  • \$\begingroup\$ @m90 ooh that's nice! Thx! \$\endgroup\$
    – 640KB
    Jul 14, 2022 at 13:26
2
\$\begingroup\$

Brachylog, 5 bytes

ġ₂↔ᵐc

Try it online!

Explanation

ġ₂         Split the list in groups of 2 consecutive elements
  ↔ᵐ       Map reverse
    c      Concatenate
\$\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.