Programming Search⌘K

Taskcore

Compute the permutations of a list

Also called permutations, all orders of a list, all arrangements of the items, next permutation, itertools.permutations, permute a list.

Make each order of the items of a list of integers, in the lexicographic order of the positions.

Task

Make each order of the items of a list of integers. The function permutations(items) returns the orders in the lexicographic order of the positions: the input order comes first, and the reverse order comes last. For example, permutations([1, 2, 3]) is [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]].

A list of n items has n! orders, so the length is at most 8, which gives 40320 orders. The empty list has one order, the empty list. Items can be equal, and equal items at different positions count as different items. The items are 32-bit signed integers.

Solutions

Language Make each order
Python [list(p) for p in itertools.permutations(items)]
JavaScript, TypeScript recursion that adds each unused item to a path, then a copy of the full path
Java the same recursion, with a boolean[] of used positions and path.clone()
C# the same recursion, with (int[])path.Clone()
Go the same recursion, with slices.Clone(path)
Rust the same recursion, with path.clone()
C the next order of an array of indices, in a do loop
C++ std::next_permutation over a vector of indices from std::iota
Bash recursion that takes each argument in turn, with local variables
  • The order. "The permutation tuples are emitted in lexicographic order according to the order of the input iterable. If the input iterable is sorted, the output tuples will be produced in sorted order."1 The recursion gives the same order, because it tries the positions from the first to the last at each depth.
  • Positions, not values. "Elements are treated as unique based on their position, not on their value."1 Thus [1, 1, 2] gives 6 orders, and some of them are equal. The C and C++ solutions get this rule from the indices: the indices are all different, so each order of the indices is one order of the positions.
  • The count grows fast. The number of orders of n items is n!. For 10 items it is 3628800, and for 13 items it is more than a 32-bit integer can hold. Python can count the orders with math.perm(n) before it makes them.
  • Lazy orders. itertools.permutations makes one order at a time. Use the iterator directly when you need only some of the orders, or when you can stop early. The solution makes a list because the task asks for all the orders.
  • C. The caller gives the array out and its capacity in items. Order r is at out[r * n] to out[r * n + n - 1]. The function returns -1 when n is more than 12 or when the orders do not fit, and then it writes nothing.
  • Bash. Each argument is one item. The function prints each order on one line.

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl.

  • empty: [] gives one order, [[]], because 0! is 1. Python agrees: list(itertools.permutations([])) is [()].
  • single: [7] gives [7](/languages/all/#7).
  • duplicates: [1, 1, 2] gives 6 orders, with each distinct order two times.
  • unsorted: [3, 1, 2] gives [3, 1, 2] first and [2, 1, 3] last. The orders are not sorted by value.
  • extremes: -2147483648 and 2147483647 stay as they are.

Pitfalls

  • Python equal items give equal orders. permutations treats items "as unique based on their position, not on their value."1 Thus [1, 1, 2] gives 6 orders, and the first and the third are equal. To get each distinct order once, put the orders in a set:
from itertools import permutations

orders = list(permutations([1, 1, 2]))
print(len(orders), orders[0] == orders[2])
print(sorted(set(orders)))
Output
6 True
[(1, 1, 2), (1, 2, 1), (2, 1, 1)]
  • JavaScript sort compares numbers as text. To get the orders in sorted order, sort the input first. But "The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code unit values."2 Thus 10 comes before 9. Give a compare function:
const items = [10, 9, 1];
console.log(JSON.stringify([...items].sort()));
console.log(JSON.stringify([...items].sort((a, b) => a - b)));
Output
[1,10,9]
[1,9,10]
  • Java the result holds the path, not a copy. In the example, the first run adds path itself to out six times. The recursion then removes all the items from path, so each item of out is the same empty list. The copy constructor "Constructs a list containing the elements of the specified collection"3, so the second run keeps each order:
import java.util.ArrayList;
import java.util.List;

public class Main {
  static void visit(List<Integer> items, List<Integer> path, List<List<Integer>> out, boolean copy) {
    if (path.size() == items.size()) {
      out.add(copy ? new ArrayList<>(path) : path);
      return;
    }
    for (Integer x : items) {
      if (path.contains(x)) {
        continue;
      }
      path.add(x);
      visit(items, path, out, copy);
      path.remove(path.size() - 1);
    }
  }

  public static void main(String[] args) {
    for (boolean copy : new boolean[] {false, true}) {
      List<List<Integer>> out = new ArrayList<>();
      visit(List.of(1, 2, 3), new ArrayList<>(), out, copy);
      System.out.println(out);
    }
  }
}
Output
[[], [], [], [], [], []]
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
  • C# the count of orders overflows with no error. "By default, arithmetic operations occur in an unchecked context."4 There, "the result is truncated by discarding any high-order bits that don't fit in the destination type."4 Thus 13! in an int is a wrong number. checked gives an OverflowException:
using System;

int f = 1;
for (int n = 1; n <= 13; n++)
{
    f *= n;
}
Console.WriteLine(f);

int g = 1;
try
{
    for (int n = 1; n <= 13; n++)
    {
        g = checked(g * n);
    }
}
catch (OverflowException)
{
    Console.WriteLine($"OverflowException after {g}");
}
Output
1932053504
OverflowException after 479001600
  • Go append can share the array of the prefix. "If the capacity of s is not large enough to fit the additional values, append allocates a new, sufficiently large underlying array"5. "Otherwise, append re-uses the underlying array."5 In the example, prefix has room for 4 items, so a and b use its array, and the second append changes a. A recursion that gives append(prefix, x) to each call has the same problem. Copy each full order, as the solution does with slices.Clone:
package main

import "fmt"

func main() {
	prefix := make([]int, 1, 4)
	prefix[0] = 1
	a := append(prefix, 2)
	b := append(prefix, 3)
	fmt.Println(a, b)
}
Output
[1 3] [1 3]
  • Rust swaps do not give the lexicographic order. A common recursion swaps the item at depth k with each later item, and swap "Swaps two elements in the slice."6 This makes all n! orders, but in a different order: 321 comes before 312. Sort the result, or use the recursion with a list of used positions, as the solution does:
fn swaps(v: &mut Vec<i32>, k: usize, out: &mut Vec<String>) {
    if k == v.len() {
        out.push(v.iter().map(|x| x.to_string()).collect());
        return;
    }
    for i in k..v.len() {
        v.swap(k, i);
        swaps(v, k + 1, out);
        v.swap(k, i);
    }
}

fn main() {
    let mut out = Vec::new();
    swaps(&mut vec![1, 2, 3], 0, &mut out);
    println!("{}", out.join(" "));
    let mut sorted = out.clone();
    sorted.sort();
    println!("{}", sorted.join(" "));
}
Output
123 132 213 231 321 312
123 132 213 231 312 321
  • C n! does not fit in an int for n of 13 or more. "When signed integer arithmetic operation overflows (the result does not fit in the result type), the behavior is undefined"7. 13! is 6227020800, which is more than INT32_MAX. The example counts in uint64_t, so it does not overflow. The solution limits n to 12, and counts in size_t:
#include <stdint.h>
#include <stdio.h>

int main(void) {
    uint64_t f = 1;
    for (int n = 1; n <= 13; n++) {
        f *= (uint64_t)n;
        if (n >= 12) {
            // 1 means that n! does not fit in a 32-bit int.
            printf("%d! = %llu %d\n", n, (unsigned long long)f, f > INT32_MAX);
        }
    }
    return 0;
}
Output
12! = 479001600 0
13! = 6227020800 1
  • C++ next_permutation starts from the given order. It "Permutes the target range [first, last) into the lexicographically next permutation."8 After the last order, it "transforms the range into the lexicographically first permutation"8 and returns false. Thus a loop from {2, 1, 3} sees only 4 orders, the ones that come after it. Also, it orders by value, so {1, 1, 2} gives 3 orders, not 6. Sort the input first to get all the distinct orders, or permute indices, as the solution does:
#include <algorithm>
#include <iostream>
#include <vector>

static int count_orders(std::vector<int> v) {
    int n = 0;
    do {
        n++;
    } while (std::next_permutation(v.begin(), v.end()));
    return n;
}

int main() {
    std::cout << count_orders({1, 2, 3}) << '\n';
    std::cout << count_orders({2, 1, 3}) << '\n';
    std::cout << count_orders({1, 1, 2}) << '\n';
}
Output
6
4
3
  • Bash a recursive function needs local variables. "Ordinarily, variables and their values are shared between a function and its caller."9 In perm, the inner call changes i and rest of the outer call, so the loop stops after the first order. perm_local declares them with local:
perm() { # perm PREFIX ITEM...: no local variables
  prefix=$1
  shift
  if (($# == 0)); then
    echo "$prefix"
    return
  fi
  rest=("$@")
  for ((i = 0; i < ${#rest[@]}; i++)); do
    perm "$prefix${rest[i]}" "${rest[@]:0:i}" "${rest[@]:i+1}"
  done
}

perm_local() { # perm_local PREFIX ITEM...
  local prefix=$1 i
  shift
  if (($# == 0)); then
    echo "$prefix"
    return
  fi
  local -a rest=("$@")
  for ((i = 0; i < ${#rest[@]}; i++)); do
    perm_local "$prefix${rest[i]}" "${rest[@]:0:i}" "${rest[@]:i+1}"
  done
}

perm "" 1 2 3 | paste -sd ' ' -
perm_local "" 1 2 3 | paste -sd ' ' -
Output
123
123 132 213 231 312 321

Code

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

permutations.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compute-the-permutations-of-a-list/.

import itertools


def permutations(items: list[int]) -> list[list[int]]:
    """Return each order of the items, in the lexicographic order of the positions."""
    return [list(p) for p in itertools.permutations(items)]
test_permutations.py 22 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compute-the-permutations-of-a-list/.

import pytest

from permutations import permutations

CASES = {
    "three": ([1, 2, 3], [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]),
    "two": ([5, 6], [[5, 6], [6, 5]]),
    "empty": ([], [[]]),
    "single": ([7], [[7]]),
    "duplicates": ([1, 1, 2], [[1, 1, 2], [1, 2, 1], [1, 1, 2], [1, 2, 1], [2, 1, 1], [2, 1, 1]]),
    "unsorted": ([3, 1, 2], [[3, 1, 2], [3, 2, 1], [1, 3, 2], [1, 2, 3], [2, 3, 1], [2, 1, 3]]),
    "extremes": ([-2147483648, 2147483647], [[-2147483648, 2147483647], [2147483647, -2147483648]]),
}


@pytest.mark.parametrize("name", CASES)
def test_permutations(name):
    items, want = CASES[name]
    assert permutations(items) == want
permutations.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-permutations-of-a-list/.

#include "permutations.hpp"

#include <algorithm>
#include <cstddef>
#include <numeric>

std::vector<std::vector<std::int32_t>> permutations(const std::vector<std::int32_t> &items) {
    // next_permutation orders by value. The indices 0, 1, ... are sorted and
    // all different, so their orders are the orders of the positions, also
    // when items has equal values.
    std::vector<std::size_t> idx(items.size());
    std::iota(idx.begin(), idx.end(), std::size_t{0});
    std::vector<std::vector<std::int32_t>> out;
    do {
        std::vector<std::int32_t> order;
        order.reserve(idx.size());
        for (std::size_t i : idx) {
            order.push_back(items[i]);
        }
        out.push_back(std::move(order));
    } while (std::next_permutation(idx.begin(), idx.end()));
    return out;
}
permutations.hpp 11 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-permutations-of-a-list/.

#pragma once

#include <cstdint>
#include <vector>

// permutations returns each order of the items, in the lexicographic order of
// the positions.
std::vector<std::vector<std::int32_t>> permutations(const std::vector<std::int32_t> &items);
test_permutations.cpp 36 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-permutations-of-a-list/.

#include "permutations.hpp"

#include <cstdint>
#include <iostream>
#include <string_view>
#include <vector>

static int failures = 0;

using List = std::vector<std::int32_t>;
using Lists = std::vector<List>;

static void check(std::string_view name, const List &items, const Lists &want) {
    if (permutations(items) != want) {
        std::cerr << "case " << name << " failed\n";
        failures++;
    }
}

int main() {
    check("three", List{1, 2, 3}, Lists{{1, 2, 3}, {1, 3, 2}, {2, 1, 3}, {2, 3, 1}, {3, 1, 2}, {3, 2, 1}});
    check("two", List{5, 6}, Lists{{5, 6}, {6, 5}});
    check("empty", List{}, Lists{List{}});
    check("single", List{7}, Lists{{7}});
    check("duplicates", List{1, 1, 2}, Lists{{1, 1, 2}, {1, 2, 1}, {1, 1, 2}, {1, 2, 1}, {2, 1, 1}, {2, 1, 1}});
    check("unsorted", List{3, 1, 2}, Lists{{3, 1, 2}, {3, 2, 1}, {1, 3, 2}, {1, 2, 3}, {2, 3, 1}, {2, 1, 3}});
    check("extremes", List{INT32_MIN, INT32_MAX}, Lists{{INT32_MIN, INT32_MAX}, {INT32_MAX, INT32_MIN}});
    if (failures > 0) {
        return 1;
    }
    std::cout << "all cases pass\n";
    return 0;
}
Permutations.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-permutations-of-a-list/.

import java.util.ArrayList;
import java.util.List;

final class Permutations {
  private Permutations() {}

  /** Returns each order of the items, in the lexicographic order of the positions. */
  static int[][] permutations(int[] items) {
    List<int[]> out = new ArrayList<>();
    visit(items, new boolean[items.length], new int[items.length], 0, out);
    return out.toArray(new int[0][]);
  }

  private static void visit(int[] items, boolean[] used, int[] path, int depth, List<int[]> out) {
    if (depth == items.length) {
      // path changes later, so add a copy.
      out.add(path.clone());
      return;
    }
    for (int i = 0; i < items.length; i++) {
      if (used[i]) {
        continue;
      }
      used[i] = true;
      path[depth] = items[i];
      visit(items, used, path, depth + 1, out);
      used[i] = false;
    }
  }
}
PermutationsTest.java 28 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-permutations-of-a-list/.

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 PermutationsTest {
  static Stream<Arguments> cases() {
    return Stream.of(
        Arguments.of("three", new int[] {1, 2, 3}, new int[][] {{1, 2, 3}, {1, 3, 2}, {2, 1, 3}, {2, 3, 1}, {3, 1, 2}, {3, 2, 1}}),
        Arguments.of("two", new int[] {5, 6}, new int[][] {{5, 6}, {6, 5}}),
        Arguments.of("empty", new int[] {}, new int[][] {{}}),
        Arguments.of("single", new int[] {7}, new int[][] {{7}}),
        Arguments.of("duplicates", new int[] {1, 1, 2}, new int[][] {{1, 1, 2}, {1, 2, 1}, {1, 1, 2}, {1, 2, 1}, {2, 1, 1}, {2, 1, 1}}),
        Arguments.of("unsorted", new int[] {3, 1, 2}, new int[][] {{3, 1, 2}, {3, 2, 1}, {1, 3, 2}, {1, 2, 3}, {2, 3, 1}, {2, 1, 3}}),
        Arguments.of("extremes", new int[] {Integer.MIN_VALUE, Integer.MAX_VALUE}, new int[][] {{Integer.MIN_VALUE, Integer.MAX_VALUE}, {Integer.MAX_VALUE, Integer.MIN_VALUE}}));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("cases")
  void permutations(String name, int[] items, int[][] want) {
    assertArrayEquals(want, Permutations.permutations(items), name);
  }
}
permutations.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-permutations-of-a-list/.

#include "permutations.h"

#include <stdbool.h>

// next_order changes idx to the next order of the indices in lexicographic
// order. It returns false when idx is the last order.
static bool next_order(size_t *idx, size_t n) {
    if (n < 2) {
        return false;
    }
    // Find the last j with idx[j] < idx[j + 1].
    size_t j = n - 1;
    while (j > 0 && idx[j - 1] > idx[j]) {
        j--;
    }
    if (j == 0) {
        return false;
    }
    j--;
    // Find the last l with idx[j] < idx[l], and swap them.
    size_t l = n - 1;
    while (idx[l] < idx[j]) {
        l--;
    }
    size_t t = idx[j];
    idx[j] = idx[l];
    idx[l] = t;
    // Reverse the tail after j.
    for (size_t a = j + 1, b = n - 1; a < b; a++, b--) {
        t = idx[a];
        idx[a] = idx[b];
        idx[b] = t;
    }
    return true;
}

int permutations(const int32_t *items, size_t n, int32_t *out, size_t cap, size_t *count) {
    if (n > PERMUTATIONS_MAX) {
        return -1;
    }
    size_t total = 1;
    for (size_t k = 2; k <= n; k++) {
        total *= k;
    }
    if (n > 0 && total > cap / n) {
        return -1;
    }
    // The indices are all different, so their orders are the orders of the
    // positions, also when items has equal values.
    size_t idx[PERMUTATIONS_MAX];
    for (size_t k = 0; k < n; k++) {
        idx[k] = k;
    }
    size_t r = 0;
    do {
        for (size_t k = 0; k < n; k++) {
            out[r * n + k] = items[idx[k]];
        }
        r++;
    } while (next_order(idx, n));
    *count = total;
    return 0;
}
permutations.h 21 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-permutations-of-a-list/.

#ifndef PERMUTATIONS_H
#define PERMUTATIONS_H

#include <stddef.h>
#include <stdint.h>

// PERMUTATIONS_MAX is the largest n. 12! is 479001600, which fits in a
// 32-bit size_t.
#define PERMUTATIONS_MAX 12

// permutations writes each order of the n items to out, in the lexicographic
// order of the positions. Order r is at out[r * n] to out[r * n + n - 1]. It
// stores the number of orders, n!, in *count and returns 0. It returns -1
// when n > PERMUTATIONS_MAX, or when out has room for fewer than n! * n
// items. Then it writes nothing.
int permutations(const int32_t *items, size_t n, int32_t *out, size_t cap, size_t *count);

#endif
test_permutations.c 60 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-permutations-of-a-list/.

#include "permutations.h"

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

static int failures = 0;

#define L(...) {__VA_ARGS__}

// C has no empty array, so an empty list has a 0 in it. N, M and C give the
// real lengths: N items, M items in all the orders, C orders.
#define CHECK(name, n, given, m, c, flat)                                      \
    do {                                                                       \
        const int32_t g[] = given;                                             \
        const int32_t want[] = flat;                                           \
        int32_t out[sizeof want / sizeof want[0]];                             \
        size_t count = 99;                                                     \
        int ok = permutations(g, n, out, m, &count) == 0 && count == c;        \
        ok = ok && memcmp(out, want, (size_t)(m) * sizeof out[0]) == 0;        \
        if (!ok) {                                                             \
            fprintf(stderr, "case %s failed\n", name);                         \
            failures++;                                                        \
        }                                                                      \
    } while (0)

int main(void) {
    CHECK("three", 3, L(1, 2, 3), 18, 6, L(1, 2, 3, 1, 3, 2, 2, 1, 3, 2, 3, 1, 3, 1, 2, 3, 2, 1));
    CHECK("two", 2, L(5, 6), 4, 2, L(5, 6, 6, 5));
    CHECK("empty", 0, L(0), 0, 1, L(0));
    CHECK("single", 1, L(7), 1, 1, L(7));
    CHECK("duplicates", 3, L(1, 1, 2), 18, 6, L(1, 1, 2, 1, 2, 1, 1, 1, 2, 1, 2, 1, 2, 1, 1, 2, 1, 1));
    CHECK("unsorted", 3, L(3, 1, 2), 18, 6, L(3, 1, 2, 3, 2, 1, 1, 3, 2, 1, 2, 3, 2, 3, 1, 2, 1, 3));
    CHECK("extremes", 2, L(INT32_MIN, INT32_MAX), 4, 2, L(INT32_MIN, INT32_MAX, INT32_MAX, INT32_MIN));

    // out has room for 3 items, and the 2 orders need 4.
    const int32_t two[] = {1, 2};
    int32_t small[3] = {0, 0, 0};
    size_t count = 0;
    if (permutations(two, 2, small, 3, &count) != -1 || small[0] != 0) {
        fprintf(stderr, "case small failed\n");
        failures++;
    }

    // 13 items are more than PERMUTATIONS_MAX.
    const int32_t many[13] = {0};
    if (permutations(many, 13, small, 3, &count) != -1) {
        fprintf(stderr, "case max failed\n");
        failures++;
    }

    if (failures > 0) {
        return 1;
    }
    printf("all cases pass\n");
    return 0;
}
Permutations.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-permutations-of-a-list/.

using System.Collections.Generic;

public static class Permutations
{
    // Of returns each order of the items, in the lexicographic order of the positions.
    public static int[][] Of(int[] items)
    {
        var output = new List<int[]>();
        Visit(items, new bool[items.Length], new int[items.Length], 0, output);
        return output.ToArray();
    }

    private static void Visit(int[] items, bool[] used, int[] path, int depth, List<int[]> output)
    {
        if (depth == items.Length)
        {
            // path changes later, so add a copy.
            output.Add((int[])path.Clone());
            return;
        }
        for (int i = 0; i < items.Length; i++)
        {
            if (used[i])
            {
                continue;
            }
            used[i] = true;
            path[depth] = items[i];
            Visit(items, used, path, depth + 1, output);
            used[i] = false;
        }
    }
}
PermutationsTests.cs 26 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-permutations-of-a-list/.

using Xunit;

public sealed class PermutationsTests
{
    public static TheoryData<string, int[], int[][]> Cases => new()
    {
        { "three", new[] { 1, 2, 3 }, new[] { new[] { 1, 2, 3 }, new[] { 1, 3, 2 }, new[] { 2, 1, 3 }, new[] { 2, 3, 1 }, new[] { 3, 1, 2 }, new[] { 3, 2, 1 } } },
        { "two", new[] { 5, 6 }, new[] { new[] { 5, 6 }, new[] { 6, 5 } } },
        { "empty", new int[0], new[] { new int[0] } },
        { "single", new[] { 7 }, new[] { new[] { 7 } } },
        { "duplicates", new[] { 1, 1, 2 }, new[] { new[] { 1, 1, 2 }, new[] { 1, 2, 1 }, new[] { 1, 1, 2 }, new[] { 1, 2, 1 }, new[] { 2, 1, 1 }, new[] { 2, 1, 1 } } },
        { "unsorted", new[] { 3, 1, 2 }, new[] { new[] { 3, 1, 2 }, new[] { 3, 2, 1 }, new[] { 1, 3, 2 }, new[] { 1, 2, 3 }, new[] { 2, 3, 1 }, new[] { 2, 1, 3 } } },
        { "extremes", new[] { int.MinValue, int.MaxValue }, new[] { new[] { int.MinValue, int.MaxValue }, new[] { int.MaxValue, int.MinValue } } },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void Check(string name, int[] items, int[][] want)
    {
        Assert.NotNull(name);
        Assert.Equal(want, Permutations.Of(items));
    }
}
permutations.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-permutations-of-a-list/.

/**
 * @param {number[]} items
 * @returns {number[][]}
 */
export function permutations(items) {
  const out = [];
  const used = items.map(() => false);
  const path = [];
  // visit adds each unused item to path in turn, from the first position
  // to the last, so the orders come in the lexicographic order of positions.
  const visit = () => {
    if (path.length === items.length) {
      out.push([...path]);
      return;
    }
    for (let i = 0; i < items.length; i++) {
      if (used[i]) continue;
      used[i] = true;
      path.push(items[i]);
      visit();
      path.pop();
      used[i] = false;
    }
  };
  visit();
  return out;
}
permutations.test.js 23 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-permutations-of-a-list/.

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

import { permutations } from "./permutations.js";

const cases = [
  ["three", [1, 2, 3], [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]],
  ["two", [5, 6], [[5, 6], [6, 5]]],
  ["empty", [], [[]]],
  ["single", [7], [[7]]],
  ["duplicates", [1, 1, 2], [[1, 1, 2], [1, 2, 1], [1, 1, 2], [1, 2, 1], [2, 1, 1], [2, 1, 1]]],
  ["unsorted", [3, 1, 2], [[3, 1, 2], [3, 2, 1], [1, 3, 2], [1, 2, 3], [2, 3, 1], [2, 1, 3]]],
  ["extremes", [-2147483648, 2147483647], [[-2147483648, 2147483647], [2147483647, -2147483648]]],
];

for (const [name, items, want] of cases) {
  test(name, () => {
    assert.deepEqual(permutations(items), want);
  });
}
permutations.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-permutations-of-a-list/.

export function permutations(items: readonly number[]): number[][] {
  const out: number[][] = [];
  const used = items.map(() => false);
  const path: number[] = [];
  // visit adds each unused item to path in turn, from the first position
  // to the last, so the orders come in the lexicographic order of positions.
  const visit = (): void => {
    if (path.length === items.length) {
      out.push([...path]);
      return;
    }
    for (let i = 0; i < items.length; i++) {
      if (used[i]) continue;
      used[i] = true;
      path.push(items[i]);
      visit();
      path.pop();
      used[i] = false;
    }
  };
  visit();
  return out;
}
permutations.test.ts 23 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-permutations-of-a-list/.

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

import { permutations } from "./permutations.ts";

const cases: [string, number[], number[][]][] = [
  ["three", [1, 2, 3], [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]],
  ["two", [5, 6], [[5, 6], [6, 5]]],
  ["empty", [], [[]]],
  ["single", [7], [[7]]],
  ["duplicates", [1, 1, 2], [[1, 1, 2], [1, 2, 1], [1, 1, 2], [1, 2, 1], [2, 1, 1], [2, 1, 1]]],
  ["unsorted", [3, 1, 2], [[3, 1, 2], [3, 2, 1], [1, 3, 2], [1, 2, 3], [2, 3, 1], [2, 1, 3]]],
  ["extremes", [-2147483648, 2147483647], [[-2147483648, 2147483647], [2147483647, -2147483648]]],
];

for (const [name, items, want] of cases) {
  test(name, () => {
    assert.deepEqual(permutations(items), want);
  });
}
permutations.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-permutations-of-a-list/.

// Package permutations computes all the orders of a list.
package permutations

import "slices"

// Permutations returns each order of the items, in the lexicographic order
// of the positions. Each order has its own array.
func Permutations(items []int32) [][]int32 {
	var out [][]int32
	used := make([]bool, len(items))
	path := make([]int32, 0, len(items))
	var visit func()
	visit = func() {
		if len(path) == len(items) {
			// path changes later, so add a copy.
			out = append(out, slices.Clone(path))
			return
		}
		for i, x := range items {
			if used[i] {
				continue
			}
			used[i] = true
			path = append(path, x)
			visit()
			path = path[:len(path)-1]
			used[i] = false
		}
	}
	visit()
	return out
}
permutations_test.go 41 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-permutations-of-a-list/.

package permutations

import (
	"math"
	"slices"
	"testing"
)

var cases = []struct {
	name  string
	items []int32
	want  [][]int32
}{
	{"three", []int32{1, 2, 3}, [][]int32{{1, 2, 3}, {1, 3, 2}, {2, 1, 3}, {2, 3, 1}, {3, 1, 2}, {3, 2, 1}}},
	{"two", []int32{5, 6}, [][]int32{{5, 6}, {6, 5}}},
	{"empty", []int32{}, [][]int32{{}}},
	{"single", []int32{7}, [][]int32{{7}}},
	{"duplicates", []int32{1, 1, 2}, [][]int32{{1, 1, 2}, {1, 2, 1}, {1, 1, 2}, {1, 2, 1}, {2, 1, 1}, {2, 1, 1}}},
	{"unsorted", []int32{3, 1, 2}, [][]int32{{3, 1, 2}, {3, 2, 1}, {1, 3, 2}, {1, 2, 3}, {2, 3, 1}, {2, 1, 3}}},
	{"extremes", []int32{math.MinInt32, math.MaxInt32}, [][]int32{{math.MinInt32, math.MaxInt32}, {math.MaxInt32, math.MinInt32}}},
}

func TestPermutations(t *testing.T) {
	for _, c := range cases {
		got := Permutations(c.items)
		if !slices.EqualFunc(got, c.want, slices.Equal[[]int32]) {
			t.Errorf("%s: got %v, want %v", c.name, got, c.want)
		}
	}
}

func TestPermutationsOwnArrays(t *testing.T) {
	got := Permutations([]int32{1, 2})
	got[0][0] = 99
	if got[1][1] != 1 {
		t.Errorf("a change to one order changed another: %v", got)
	}
}
permutations.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-permutations-of-a-list/.

/// Returns each order of the items, in the lexicographic order of the positions.
pub fn permutations(items: &[i32]) -> Vec<Vec<i32>> {
    let mut out = Vec::new();
    let mut used = vec![false; items.len()];
    let mut path = Vec::with_capacity(items.len());
    visit(items, &mut used, &mut path, &mut out);
    out
}

fn visit(items: &[i32], used: &mut [bool], path: &mut Vec<i32>, out: &mut Vec<Vec<i32>>) {
    if path.len() == items.len() {
        // path changes later, so add a copy.
        out.push(path.clone());
        return;
    }
    for (i, &x) in items.iter().enumerate() {
        if used[i] {
            continue;
        }
        used[i] = true;
        path.push(x);
        visit(items, used, path, out);
        path.pop();
        used[i] = false;
    }
}
tests/permutations_test.rs 20 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-permutations-of-a-list/.

use algo_compute_the_permutations_of_a_list::permutations;

#[test]
fn cases() {
    let cases: Vec<(&str, Vec<i32>, Vec<Vec<i32>>)> = vec![
        ("three", vec![1, 2, 3], vec![vec![1, 2, 3], vec![1, 3, 2], vec![2, 1, 3], vec![2, 3, 1], vec![3, 1, 2], vec![3, 2, 1]]),
        ("two", vec![5, 6], vec![vec![5, 6], vec![6, 5]]),
        ("empty", Vec::new(), vec![Vec::new()]),
        ("single", vec![7], vec![vec![7]]),
        ("duplicates", vec![1, 1, 2], vec![vec![1, 1, 2], vec![1, 2, 1], vec![1, 1, 2], vec![1, 2, 1], vec![2, 1, 1], vec![2, 1, 1]]),
        ("unsorted", vec![3, 1, 2], vec![vec![3, 1, 2], vec![3, 2, 1], vec![1, 3, 2], vec![1, 2, 3], vec![2, 3, 1], vec![2, 1, 3]]),
        ("extremes", vec![i32::MIN, i32::MAX], vec![vec![i32::MIN, i32::MAX], vec![i32::MAX, i32::MIN]]),
    ];
    for (name, items, want) in cases {
        assert_eq!(permutations(&items), want, "{name}");
    }
}
permutations.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compute-the-permutations-of-a-list/.

# permutations ITEM...
# Prints each order of the items on one line, with the items separated by
# spaces, in the lexicographic order of the positions. With no arguments, it
# prints one empty line, the one empty order.
permutations() {
  _permutations_visit "" "$@"
}

# _permutations_visit PREFIX ITEM...
# Prints PREFIX followed by each order of the items.
_permutations_visit() {
  # local keeps the variables of each call apart in the recursion.
  local prefix=$1 i
  shift
  if (($# == 0)); then
    printf '%s\n' "$prefix"
    return
  fi
  local -a rest=("$@")
  for ((i = 0; i < ${#rest[@]}; i++)); do
    _permutations_visit "${prefix:+$prefix }${rest[i]}" "${rest[@]:0:i}" "${rest[@]:i+1}"
  done
}
test_permutations.bats 27 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compute-the-permutations-of-a-list/.

bats_require_minimum_version 1.5.0

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

check() { # check WANT ITEM...
  local want got
  # %b turns each \n in WANT into a newline. The x keeps the trailing
  # newlines, which $(...) removes.
  want=$(printf '%b' "$1"; printf x)
  shift
  got=$(permutations "$@"; printf x)
  [ "$got" = "$want" ] || { printf 'got:  %q\nwant: %q\n' "$got" "$want"; return 1; }
}

@test "three" { check "1 2 3\n1 3 2\n2 1 3\n2 3 1\n3 1 2\n3 2 1\n" 1 2 3; }
@test "two" { check "5 6\n6 5\n" 5 6; }
@test "empty" { check "\n"; }
@test "single" { check "7\n" 7; }
@test "duplicates" { check "1 1 2\n1 2 1\n1 1 2\n1 2 1\n2 1 1\n2 1 1\n" 1 1 2; }
@test "unsorted" { check "3 1 2\n3 2 1\n1 3 2\n1 2 3\n2 3 1\n2 1 3\n" 3 1 2; }
@test "extremes" { check "-2147483648 2147483647\n2147483647 -2147483648\n" -2147483648 2147483647; }

References

  1. The Python Standard Library, itertools, itertools.permutations()
  2. MDN Web Docs, Array.prototype.sort(), Description
  3. Java SE 25 API, Class ArrayList, ArrayList(Collection)
  4. C# language reference, Arithmetic operators, Integer arithmetic overflow
  5. The Go Programming Language Specification, Appending to and copying slices
  6. Rust standard library, primitive type slice, swap
  7. cppreference.com, Arithmetic operators (C), Overflows
  8. cppreference.com, std::next_permutation, Description
  9. Bash Reference Manual, 3.3 Shell Functions

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