Programming Search⌘K

Taskintro

Swap two values

Also called swap, swap two variables, exchange two values, generic swap, std::swap, mem::swap, tuple swap, XOR swap, Generic swap.

Exchange the values of two variables or two items of a list: with a temporary variable, with a tuple assignment, or with std::swap or mem::swap. The XOR trick fails when both are the same place.

Task

The Rosetta Code task asks for "a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types"1. After a swap of a = 1 and b = 2, a is 2 and b is 1.

The function swap_items(xs, i, j) swaps two storage places of one list: the items at the indexes i and j. It returns a new list and does not change xs. When i equals j, the result equals xs. The C solution swaps the items in place, because C has no simple way to return a new array.

Solutions

There are three common ways:

  • A temporary variable. "The simplest and probably most widely used method to swap two variables is to use a third temporary variable"2: tmp = a; a = b; b = tmp. This works in all languages and for all types.
  • A tuple assignment. a, b = b, a assigns two values at once. "This is shorthand for an operation involving an intermediate data structure: in Python and Julia, a tuple; in Ruby, an array."2 The right side is computed first: "while evaluating an assignment, the right-hand side is evaluated before the left-hand side"3.
  • A library function. C++ std::swap "Exchanges the given values."4 Rust std::mem::swap "Swaps the values at two mutable locations, without deinitializing either one."5 For two items of one slice, Rust has slice::swap(i, j).
Language Swap of two items Copy of the list
Python out[i], out[j] = out[j], out[i] list(xs)
JavaScript, TypeScript [out[i], out[j]] = [out[j], out[i]] [...xs]
Java a temporary variable xs.clone()
C# (copy[i], copy[j]) = (copy[j], copy[i]) (long[])xs.Clone()
Go out[i], out[j] = out[j], out[i] slices.Clone(xs)
Rust out.swap(i, j) xs.to_vec()
C a temporary variable, in place none
C++ std::swap(xs[i], xs[j]) the parameter, which is passed by value
Bash a temporary variable in an array local -a xs=("$@")

In Python, the tuple swap of two variables is one line:

a, b = 1, 2
a, b = b, a
print(a, b)

xs = [1, 2, 3, 4]
xs[0], xs[3] = xs[3], xs[0]
print(xs)
Output
2 1
[4, 2, 3, 1]

In Rust, std::mem::swap(&mut out[i], &mut out[j]) does not compile, because it needs two mutable borrows of one slice at the same time. slice::swap does the same job with two indexes.

Edge cases

  • The same index. swap_items([1, 2, 3], 1, 1) gives [1, 2, 3]. A list with one item has only this case.
  • The higher index first. The order of i and j does not matter: (3, 0) gives the same list as (0, 3).
  • Equal values. [4, 4] stays [4, 4].
  • Negative values and the limits of 32 bits. [2147483647, -2147483648] gives [-2147483648, 2147483647]. A swap that copies values cannot overflow.

Pitfalls

  • Two assignments without a temporary variable. a = b; b = a loses the first value of a: both variables get the value of b.
  • The XOR swap. x ^= y; y ^= x; x ^= y swaps two integers with no temporary variable. But "the algorithm fails if x and y use the same storage location, since the value stored in that location will be zeroed out by the first XOR instruction"6:

This code runs but gives a wrong answer on purpose.

def xor_swap(xs, i, j):
    xs[i] ^= xs[j]
    xs[j] ^= xs[i]
    xs[i] ^= xs[j]


xs = [1, 2, 3]
xor_swap(xs, 0, 2)
print(xs)
xor_swap(xs, 1, 1)
print(xs)
Output
[3, 2, 1]
[3, 0, 1]

The trick is also not faster: "On modern CPU architectures, the XOR technique can be slower than using a temporary variable to do swapping."6 Use a temporary variable, a tuple assignment or the library function.

  • The swap by addition. a = a + b; b = a - b; a = a - b has the same problem with one place, and more: "When swapping variables of a fixed size, arithmetic overflow becomes an issue."2 With 32-bit integers, 2147483647 + 1 overflows.
  • A function that gets copies. In Python, Java and JavaScript, a function gets the values of its arguments. A function swap(a, b) that swaps its parameters does not change the variables of the caller:

This code runs but gives a wrong answer on purpose.

def swap(a, b):
    a, b = b, a


x, y = 1, 2
swap(x, y)
print(x, y)
Output
1 2

Swap the variables where they are, or swap two items of a list or the fields of an object that the function gets. C and C++ pass pointers or references: void swap(int *a, int *b) and std::swap(T& a, T& b).

  • A line before [a, b] = [b, a] in JavaScript. Without a semicolon at the end of the line before, JavaScript reads [a, b] as an index into the value on that line.

Code

The build runs the native tests of each language in a pinned toolchain.

swap.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/swap-two-values/.


def swap_items(xs: list[int], i: int, j: int) -> list[int]:
    """Return a copy of xs with the items at i and j swapped. Python
    computes the right side, a tuple of two values, before it assigns
    them to the targets on the left."""
    out = list(xs)
    out[i], out[j] = out[j], out[i]
    return out


if __name__ == "__main__":
    a, b = 1, 2
    a, b = b, a
    print(a, b, swap_items([1, 2, 3], 0, 2))
test_swap.py 26 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/swap-two-values/.

import pytest

from swap import swap_items

CASES = [
    ("first-and-last", [1, 2, 3], 0, 2, [3, 2, 1]),
    ("middle-pair", [10, 20, 30, 40], 1, 2, [10, 30, 20, 40]),
    ("two-items", [5, 7], 0, 1, [7, 5]),
    ("single-item", [9], 0, 0, [9]),
    ("same-index", [1, 2, 3], 1, 1, [1, 2, 3]),
    ("higher-index-first", [1, 2, 3, 4], 3, 0, [4, 2, 3, 1]),
    ("equal-values", [4, 4], 0, 1, [4, 4]),
    ("negative-values", [-1, 0, 1], 0, 2, [1, 0, -1]),
    ("int32-extremes", [2147483647, -2147483648], 0, 1, [-2147483648, 2147483647]),
    ("eight-items", [1, 2, 3, 4, 5, 6, 7, 8], 2, 6, [1, 2, 7, 4, 5, 6, 3, 8]),
]


@pytest.mark.parametrize(("name", "xs", "i", "j", "want"), CASES, ids=[c[0] for c in CASES])
def test_swap_items(name, xs, i, j, want):
    before = list(xs)
    assert swap_items(xs, i, j) == want
    assert xs == before
swap.hppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/swap-two-values/.

#ifndef SWAP_HPP
#define SWAP_HPP

#include <cstddef>
#include <utility>
#include <vector>

// Returns a copy of xs with the items at i and j swapped. xs is a copy,
// because the function takes it by value. std::swap exchanges the two
// values with moves.
inline std::vector<long long> swap_items(std::vector<long long> xs, std::size_t i, std::size_t j) {
    std::swap(xs[i], xs[j]);
    return xs;
}

#endif
test_swap.cpp 48 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/swap-two-values/.

#include <cstddef>
#include <cstdio>
#include <vector>

#include "swap.hpp"

namespace {

struct test_case {
    const char* name;
    std::vector<long long> xs;
    std::size_t i;
    std::size_t j;
    std::vector<long long> want;
};

const test_case cases[] = {
    {"first-and-last", {1, 2, 3}, 0, 2, {3, 2, 1}},
    {"middle-pair", {10, 20, 30, 40}, 1, 2, {10, 30, 20, 40}},
    {"two-items", {5, 7}, 0, 1, {7, 5}},
    {"single-item", {9}, 0, 0, {9}},
    {"same-index", {1, 2, 3}, 1, 1, {1, 2, 3}},
    {"higher-index-first", {1, 2, 3, 4}, 3, 0, {4, 2, 3, 1}},
    {"equal-values", {4, 4}, 0, 1, {4, 4}},
    {"negative-values", {-1, 0, 1}, 0, 2, {1, 0, -1}},
    {"int32-extremes", {2147483647, -2147483648LL}, 0, 1, {-2147483648LL, 2147483647}},
    {"eight-items", {1, 2, 3, 4, 5, 6, 7, 8}, 2, 6, {1, 2, 7, 4, 5, 6, 3, 8}},
};

}  // namespace

int main() {
    int failures = 0;
    for (const auto& c : cases) {
        if (swap_items(c.xs, c.i, c.j) != c.want) {
            std::printf("FAIL %s\n", c.name);
            ++failures;
        }
    }
    if (failures != 0) {
        return 1;
    }
    std::printf("ok\n");
    return 0;
}
Swap.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/swap-two-values/.

/** Swap two values with a temporary variable. */
public final class Swap {
    private Swap() {}

    /**
     * Returns a copy of xs with the items at i and j swapped. Java has no
     * parallel assignment, so the swap keeps one value in a temporary
     * variable.
     */
    public static long[] swapItems(long[] xs, int i, int j) {
        long[] out = xs.clone();
        long tmp = out[i];
        out[i] = out[j];
        out[j] = tmp;
        return out;
    }

    public static void main(String[] args) {
        System.out.println(java.util.Arrays.toString(swapItems(new long[] {1, 2, 3}, 0, 2)));
    }
}
SwapTest.java 34 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/swap-two-values/.

import static org.junit.jupiter.api.Assertions.assertArrayEquals;

import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

class SwapTest {
    static Stream<Arguments> cases() {
        return Stream.of(
                Arguments.of("first-and-last", new long[]{1, 2, 3}, 0, 2, new long[]{3, 2, 1}),
                Arguments.of("middle-pair", new long[]{10, 20, 30, 40}, 1, 2, new long[]{10, 30, 20, 40}),
                Arguments.of("two-items", new long[]{5, 7}, 0, 1, new long[]{7, 5}),
                Arguments.of("single-item", new long[]{9}, 0, 0, new long[]{9}),
                Arguments.of("same-index", new long[]{1, 2, 3}, 1, 1, new long[]{1, 2, 3}),
                Arguments.of("higher-index-first", new long[]{1, 2, 3, 4}, 3, 0, new long[]{4, 2, 3, 1}),
                Arguments.of("equal-values", new long[]{4, 4}, 0, 1, new long[]{4, 4}),
                Arguments.of("negative-values", new long[]{-1, 0, 1}, 0, 2, new long[]{1, 0, -1}),
                Arguments.of("int32-extremes", new long[]{2147483647, -2147483648L}, 0, 1, new long[]{-2147483648L, 2147483647}),
                Arguments.of("eight-items", new long[]{1, 2, 3, 4, 5, 6, 7, 8}, 2, 6, new long[]{1, 2, 7, 4, 5, 6, 3, 8})
        );
    }

    @ParameterizedTest(name = "{0}")
    @MethodSource("cases")
    void swapItems(String name, long[] xs, int i, int j, long[] want) {
        long[] before = xs.clone();
        assertArrayEquals(want, Swap.swapItems(xs, i, j), name);
        assertArrayEquals(before, xs, name);
    }
}
swap.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/swap-two-values/.

#include "swap.h"

void swap_items(long long *xs, size_t i, size_t j) {
    // A temporary variable keeps the first value while the second value
    // takes its place.
    long long tmp = xs[i];
    xs[i] = xs[j];
    xs[j] = tmp;
}
swap.h 12 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/swap-two-values/.

#ifndef SWAP_H
#define SWAP_H

#include <stddef.h>

// Swaps the items at i and j of xs, in place.
void swap_items(long long *xs, size_t i, size_t j);

#endif
test_swap.c 48 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/swap-two-values/.

#include "swap.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct test_case {
    const char *name;
    size_t n;
    long long xs[8];
    size_t i, j;
    long long want[8];
};

static const struct test_case cases[] = {
    {"first-and-last", 3, {1, 2, 3}, 0, 2, {3, 2, 1}},
    {"middle-pair", 4, {10, 20, 30, 40}, 1, 2, {10, 30, 20, 40}},
    {"two-items", 2, {5, 7}, 0, 1, {7, 5}},
    {"single-item", 1, {9}, 0, 0, {9}},
    {"same-index", 3, {1, 2, 3}, 1, 1, {1, 2, 3}},
    {"higher-index-first", 4, {1, 2, 3, 4}, 3, 0, {4, 2, 3, 1}},
    {"equal-values", 2, {4, 4}, 0, 1, {4, 4}},
    {"negative-values", 3, {-1, 0, 1}, 0, 2, {1, 0, -1}},
    {"int32-extremes", 2, {2147483647, -2147483648LL}, 0, 1, {-2147483648LL, 2147483647}},
    {"eight-items", 8, {1, 2, 3, 4, 5, 6, 7, 8}, 2, 6, {1, 2, 7, 4, 5, 6, 3, 8}},
};

int main(void) {
    int failures = 0;
    for (size_t k = 0; k < sizeof cases / sizeof cases[0]; k++) {
        const struct test_case *c = &cases[k];
        long long buf[8];
        memcpy(buf, c->xs, sizeof buf);
        swap_items(buf, c->i, c->j);
        if (memcmp(buf, c->want, c->n * sizeof buf[0]) != 0) {
            printf("FAIL %s\n", c->name);
            failures++;
        }
    }
    if (failures != 0) {
        return EXIT_FAILURE;
    }
    printf("ok\n");
    return EXIT_SUCCESS;
}
Swap.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/swap-two-values/.

/// <summary>Swap two values with a tuple assignment.</summary>
public static class Swap
{
    /// <summary>
    /// Returns a copy of xs with the items at i and j swapped. The tuple on
    /// the right holds both values before the assignment to the left side.
    /// </summary>
    public static long[] SwapItems(long[] xs, int i, int j)
    {
        var copy = (long[])xs.Clone();
        (copy[i], copy[j]) = (copy[j], copy[i]);
        return copy;
    }
}
SwapTests.cs 31 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/swap-two-values/.

using Xunit;

public sealed class SwapTests
{
    public static TheoryData<string, long[], int, int, long[]> Cases => new()
    {
        { "first-and-last", new long[] { 1, 2, 3 }, 0, 2, new long[] { 3, 2, 1 } },
        { "middle-pair", new long[] { 10, 20, 30, 40 }, 1, 2, new long[] { 10, 30, 20, 40 } },
        { "two-items", new long[] { 5, 7 }, 0, 1, new long[] { 7, 5 } },
        { "single-item", new long[] { 9 }, 0, 0, new long[] { 9 } },
        { "same-index", new long[] { 1, 2, 3 }, 1, 1, new long[] { 1, 2, 3 } },
        { "higher-index-first", new long[] { 1, 2, 3, 4 }, 3, 0, new long[] { 4, 2, 3, 1 } },
        { "equal-values", new long[] { 4, 4 }, 0, 1, new long[] { 4, 4 } },
        { "negative-values", new long[] { -1, 0, 1 }, 0, 2, new long[] { 1, 0, -1 } },
        { "int32-extremes", new long[] { 2147483647, -2147483648 }, 0, 1, new long[] { -2147483648, 2147483647 } },
        { "eight-items", new long[] { 1, 2, 3, 4, 5, 6, 7, 8 }, 2, 6, new long[] { 1, 2, 7, 4, 5, 6, 3, 8 } },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void SwapItems(string name, long[] xs, int i, int j, long[] want)
    {
        Assert.NotNull(name);
        var before = (long[])xs.Clone();
        Assert.Equal(want, Swap.SwapItems(xs, i, j));
        Assert.Equal(before, xs);
    }
}
swap.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/swap-two-values/.

/**
 * Returns a copy of xs with the items at i and j swapped. The right side
 * makes a new array of the two values first, and the destructuring
 * assignment then puts them into the two places.
 */
export function swapItems(xs, i, j) {
  const out = [...xs];
  [out[i], out[j]] = [out[j], out[i]];
  return out;
}
swap.test.js 28 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/swap-two-values/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { swapItems } from "./swap.js";

const cases = [
  ["first-and-last", [1, 2, 3], 0, 2, [3, 2, 1]],
  ["middle-pair", [10, 20, 30, 40], 1, 2, [10, 30, 20, 40]],
  ["two-items", [5, 7], 0, 1, [7, 5]],
  ["single-item", [9], 0, 0, [9]],
  ["same-index", [1, 2, 3], 1, 1, [1, 2, 3]],
  ["higher-index-first", [1, 2, 3, 4], 3, 0, [4, 2, 3, 1]],
  ["equal-values", [4, 4], 0, 1, [4, 4]],
  ["negative-values", [-1, 0, 1], 0, 2, [1, 0, -1]],
  ["int32-extremes", [2147483647, -2147483648], 0, 1, [-2147483648, 2147483647]],
  ["eight-items", [1, 2, 3, 4, 5, 6, 7, 8], 2, 6, [1, 2, 7, 4, 5, 6, 3, 8]],
];

for (const [name, xs, i, j, want] of cases) {
  test(name, () => {
    const before = [...xs];
    assert.deepEqual(swapItems(xs, i, j), want);
    assert.deepEqual(xs, before);
  });
}
swap.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/swap-two-values/.

/**
 * Returns a copy of xs with the items at i and j swapped. The right side
 * makes a new array of the two values first, and the destructuring
 * assignment then puts them into the two places.
 */
export function swapItems(xs: readonly number[], i: number, j: number): number[] {
  const out = [...xs];
  [out[i], out[j]] = [out[j], out[i]];
  return out;
}
swap.test.ts 28 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/swap-two-values/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { swapItems } from "./swap.ts";

const cases: [string, number[], number, number, number[]][] = [
  ["first-and-last", [1, 2, 3], 0, 2, [3, 2, 1]],
  ["middle-pair", [10, 20, 30, 40], 1, 2, [10, 30, 20, 40]],
  ["two-items", [5, 7], 0, 1, [7, 5]],
  ["single-item", [9], 0, 0, [9]],
  ["same-index", [1, 2, 3], 1, 1, [1, 2, 3]],
  ["higher-index-first", [1, 2, 3, 4], 3, 0, [4, 2, 3, 1]],
  ["equal-values", [4, 4], 0, 1, [4, 4]],
  ["negative-values", [-1, 0, 1], 0, 2, [1, 0, -1]],
  ["int32-extremes", [2147483647, -2147483648], 0, 1, [-2147483648, 2147483647]],
  ["eight-items", [1, 2, 3, 4, 5, 6, 7, 8], 2, 6, [1, 2, 7, 4, 5, 6, 3, 8]],
];

for (const [name, xs, i, j, want] of cases) {
  test(name, () => {
    const before = [...xs];
    assert.deepEqual(swapItems(xs, i, j), want);
    assert.deepEqual(xs, before);
  });
}
swap.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/swap-two-values/.

// Package swap swaps two values with a tuple assignment.
package swap

import "slices"

// SwapItems returns a copy of xs with the items at i and j swapped. Go
// computes all values on the right before it assigns any of them.
func SwapItems(xs []int64, i, j int) []int64 {
	out := slices.Clone(xs)
	out[i], out[j] = out[j], out[i]
	return out
}
swap_test.go 41 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/swap-two-values/.

package swap

import (
	"slices"
	"testing"
)

var cases = []struct {
	name string
	xs   []int64
	i, j int
	want []int64
}{
	{"first-and-last", []int64{1, 2, 3}, 0, 2, []int64{3, 2, 1}},
	{"middle-pair", []int64{10, 20, 30, 40}, 1, 2, []int64{10, 30, 20, 40}},
	{"two-items", []int64{5, 7}, 0, 1, []int64{7, 5}},
	{"single-item", []int64{9}, 0, 0, []int64{9}},
	{"same-index", []int64{1, 2, 3}, 1, 1, []int64{1, 2, 3}},
	{"higher-index-first", []int64{1, 2, 3, 4}, 3, 0, []int64{4, 2, 3, 1}},
	{"equal-values", []int64{4, 4}, 0, 1, []int64{4, 4}},
	{"negative-values", []int64{-1, 0, 1}, 0, 2, []int64{1, 0, -1}},
	{"int32-extremes", []int64{2147483647, -2147483648}, 0, 1, []int64{-2147483648, 2147483647}},
	{"eight-items", []int64{1, 2, 3, 4, 5, 6, 7, 8}, 2, 6, []int64{1, 2, 7, 4, 5, 6, 3, 8}},
}

func TestSwapItems(t *testing.T) {
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			before := slices.Clone(c.xs)
			if got := SwapItems(c.xs, c.i, c.j); !slices.Equal(got, c.want) {
				t.Fatalf("SwapItems(%v, %d, %d) = %v, want %v", c.xs, c.i, c.j, got, c.want)
			}
			if !slices.Equal(c.xs, before) {
				t.Fatalf("SwapItems changed its input to %v", c.xs)
			}
		})
	}
}
swap.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/swap-two-values/.

/// Returns a copy of `xs` with the items at `i` and `j` swapped.
/// `slice::swap` swaps two items of one slice. The borrow rules do not
/// allow two `&mut` references into the same slice at once, so
/// `std::mem::swap(&mut out[i], &mut out[j])` does not compile.
pub fn swap_items(xs: &[i64], i: usize, j: usize) -> Vec<i64> {
    let mut out = xs.to_vec();
    out.swap(i, j);
    out
}
tests/swap_test.rs 31 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/swap-two-values/.

use algo_swap_two_values::swap_items;

#[test]
fn cases() {
    let cases: Vec<(&str, Vec<i64>, usize, usize, Vec<i64>)> = vec![
        ("first-and-last", vec![1, 2, 3], 0, 2, vec![3, 2, 1]),
        ("middle-pair", vec![10, 20, 30, 40], 1, 2, vec![10, 30, 20, 40]),
        ("two-items", vec![5, 7], 0, 1, vec![7, 5]),
        ("single-item", vec![9], 0, 0, vec![9]),
        ("same-index", vec![1, 2, 3], 1, 1, vec![1, 2, 3]),
        ("higher-index-first", vec![1, 2, 3, 4], 3, 0, vec![4, 2, 3, 1]),
        ("equal-values", vec![4, 4], 0, 1, vec![4, 4]),
        ("negative-values", vec![-1, 0, 1], 0, 2, vec![1, 0, -1]),
        ("int32-extremes", vec![2147483647, -2147483648], 0, 1, vec![-2147483648, 2147483647]),
        ("eight-items", vec![1, 2, 3, 4, 5, 6, 7, 8], 2, 6, vec![1, 2, 7, 4, 5, 6, 3, 8]),
    ];
    for (name, xs, i, j, want) in cases {
        assert_eq!(swap_items(&xs, i, j), want, "{name}");
    }
}

#[test]
fn mem_swap() {
    let mut a = String::from("left");
    let mut b = String::from("right");
    std::mem::swap(&mut a, &mut b);
    assert_eq!((a.as_str(), b.as_str()), ("right", "left"));
}
swap.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/swap-two-values/.

# swap_items i j item...: print the items, separated by spaces, with the
# items at the indexes i and j swapped. Bash has no parallel assignment, so
# the swap keeps one value in a temporary variable.
swap_items() {
  local i=$1 j=$2
  shift 2
  local -a xs=("$@")
  local tmp=${xs[i]}
  xs[i]=${xs[j]}
  xs[j]=$tmp
  printf '%s\n' "${xs[*]}"
}
test_swap.bats 67 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/swap-two-values/.

setup() {
  source "$BATS_TEST_DIRNAME/swap.sh"
}

@test "first-and-last" {
  run swap_items 0 2 1 2 3
  [ "$status" -eq 0 ]
  [ "$output" = "3 2 1" ]
}

@test "middle-pair" {
  run swap_items 1 2 10 20 30 40
  [ "$status" -eq 0 ]
  [ "$output" = "10 30 20 40" ]
}

@test "two-items" {
  run swap_items 0 1 5 7
  [ "$status" -eq 0 ]
  [ "$output" = "7 5" ]
}

@test "single-item" {
  run swap_items 0 0 9
  [ "$status" -eq 0 ]
  [ "$output" = "9" ]
}

@test "same-index" {
  run swap_items 1 1 1 2 3
  [ "$status" -eq 0 ]
  [ "$output" = "1 2 3" ]
}

@test "higher-index-first" {
  run swap_items 3 0 1 2 3 4
  [ "$status" -eq 0 ]
  [ "$output" = "4 2 3 1" ]
}

@test "equal-values" {
  run swap_items 0 1 4 4
  [ "$status" -eq 0 ]
  [ "$output" = "4 4" ]
}

@test "negative-values" {
  run swap_items 0 2 -1 0 1
  [ "$status" -eq 0 ]
  [ "$output" = "1 0 -1" ]
}

@test "int32-extremes" {
  run swap_items 0 1 2147483647 -2147483648
  [ "$status" -eq 0 ]
  [ "$output" = "-2147483648 2147483647" ]
}

@test "eight-items" {
  run swap_items 2 6 1 2 3 4 5 6 7 8
  [ "$status" -eq 0 ]
  [ "$output" = "1 2 7 4 5 6 3 8" ]
}

References

  1. Generic swap, Rosetta Code (the RosettaCodeData mirror), Task description
  2. Swap (computer programming), Wikipedia, Using a temporary variable; Parallel assignment; Swap through addition and subtraction
  3. Expressions, The Python Language Reference, 6.16 Evaluation order
  4. std::swap, cppreference.com (C++), Introduction
  5. swap in std::mem, The Rust Standard Library, Description
  6. XOR swap algorithm, Wikipedia, Proof of correctness; Reasons for avoidance in practice

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (bash)I0 not checked yet
  • the tests did not run in this build
Code (c)I0 not checked yet
  • the tests did not run in this build
Code (cpp)I0 not checked yet
  • the tests did not run in this build
Code (csharp)I0 not checked yet
  • the tests did not run in this build
Code (go)I0 not checked yet
  • the tests did not run in this build
Code (java)I0 not checked yet
  • the tests did not run in this build
Code (javascript)I0 not checked yet
  • the tests did not run in this build
Code (python)I0 not checked yet
  • the tests did not run in this build
Code (rust)I0 not checked yet
  • the tests did not run in this build
Code (typescript)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source