Skip to main content
We’ve updated our Terms of Service. A new AI Addendum clarifies how Stack Overflow utilizes AI interactions.
Code Golf

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Required fields*

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.

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

Answer*

Draft saved
Draft discarded
Cancel
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

AltStyle によって変換されたページ (->オリジナル) /