Taskcore
Compute the combinations of a list
Also called combinations, choose k items, k-subsets of a list, n choose k, itertools.combinations, all subsets of size k.
Make each choice of k items of a list of integers, with the items in list order, in the lexicographic order of the positions.
- Evidence
- Code in 10 languages
Task
Make each choice of k items of a list of integers. The function combinations(items, k) returns the choices in the lexicographic order of the positions, and the items of each choice are in the order of the list. For example, combinations([1, 2, 3, 4], 2) is [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]].
The order of the items in a choice does not matter, so [2, 1] is the same choice as [1, 2], and the function gives only [1, 2]. A list of n items has C(n, k) choices, which is n! / (k! (n - k)!). k is 0 or more. k = 0 gives one empty choice. k more than n gives no choices. The length is at most 16, and the items are 32-bit signed integers. Items can be equal, and equal items at different positions count as different items.
Solutions
| Language | Make each choice |
|---|---|
| Python | [list(c) for c in itertools.combinations(items, k)] |
| JavaScript, TypeScript | recursion that adds each item after the last chosen position to a path, then a copy of the full path |
| Java | the same recursion, with an int[] path 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 set of k increasing indices, in a loop |
| C++ | std::prev_permutation over a mask of k ones and then zeros |
| Bash | recursion that takes each argument in turn and then chooses from the arguments after it |
- The order. "The combination 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]with k = 2 gives[1, 2]two times. - Stop early. The recursion stops a loop when too few items are left to fill the choice. Thus it never starts a path that cannot reach k items, and k more than n gives no choices with no special code.
- Count before you make them.
math.comb(n, k)gives the number of choices. C(16, 8) is 12870, but C(40, 20) is 137846528820, so a list of all the choices can be too large. Use the iterator directly when you need only some of the choices. - C. The caller gives the array
outand its capacity in items. Choice r is atout[r * k]toout[r * k + k - 1]. The function returns -1 when n is more than 32, when C(n, k) does not fit in asize_t, or when the choices do not fit inout. Then it writes nothing. - Bash. The first argument is k, and each other argument is one item. The function prints each choice on one line.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
zero-k:[1, 2]with k = 0 gives one empty choice,[[]], because C(2, 0) is 1.empty:[]with k = 0 also gives[[]].k-too-large:[1, 2]with k = 3 gives[], because C(2, 3) is 0.all:[1, 2, 3]with k = 3 gives[[1, 2, 3]].duplicates:[1, 1, 2]with k = 2 gives[[1, 1], [1, 2], [1, 2]].unsorted:[3, 1, 2]with k = 2 gives[[3, 1], [3, 2], [1, 2]]. The items of a choice keep the order of the list. They are not sorted.extremes: -2147483648 and 2147483647 stay as they are.
Pitfalls
- Python combinations, combinations_with_replacement and product are different.
combinations_with_replacementgives "subsequences of elements from the input iterable allowing individual elements to be repeated more than once."1productgives each ordered pair. For 3 items and k = 2, they give 3, 6 and 9 tuples.math.combgives the "Number of ways to choose k items from n items without repetition and without order"2, which agrees withcombinations:
import itertools
import math
items = [1, 2, 3]
print(len(list(itertools.combinations(items, 2))), math.comb(3, 2))
print(len(list(itertools.combinations_with_replacement(items, 2))))
print(len(list(itertools.product(items, repeat=2))))
3 3
6
9
- JavaScript fill puts one array in each slot. To group the choices by size, do not make the groups with
Array(n).fill([]). If the value "is an object, each slot in the array will reference that object."3 Thus each push goes to the same array, and each group has all 4 choices.Array.fromwith a function makes a new array for each slot:
const combos = [[], [1], [2], [1, 2]];
const shared = Array(3).fill([]);
for (const c of combos) shared[c.length].push(c);
console.log(shared.map((b) => b.length).join(" "));
const own = Array.from({ length: 3 }, () => []);
for (const c of combos) own[c.length].push(c);
console.log(own.map((b) => b.length).join(" "));
4 4 4
1 2 1
- Java the factorial overflows a long. C(n, k) as n! / (k! (n - k)!) needs 21! for n = 21, and 21! is more than
Long.MAX_VALUE. The*=operator wraps with no error.Math.multiplyExact"Returns the product of the arguments, throwing an exception if the result overflows a long."4 The product formc * (n - i) / (i + 1)needs no factorial, and each division in it is exact:
public class Main {
public static void main(String[] args) {
long f = 1;
for (int i = 2; i <= 21; i++) {
f *= i;
}
System.out.println(f);
long g = 1;
try {
for (int i = 2; i <= 21; i++) {
g = Math.multiplyExact(g, i);
}
} catch (ArithmeticException e) {
System.out.println("ArithmeticException after " + g);
}
// C(21, 10) with no factorial: each step is exact.
long c = 1;
for (int i = 0; i < 10; i++) {
c = c * (21 - i) / (i + 1);
}
System.out.println(c);
}
}
-4249290049419214848
ArithmeticException after 2432902008176640000
352716
- C# Enumerable.Range does not accept a negative count. The first item of a choice is at a position from 0 to n - k. When k is more than n,
Enumerable.Range(0, n - k + 1)gets a negative count and throwsArgumentOutOfRangeException, because "count is less than 0."5 Check k first, as the solution does:
using System;
using System.Linq;
int n = 2;
int k = 4;
try
{
// The first item of a combination is at position 0 to n - k.
Console.WriteLine(Enumerable.Range(0, n - k + 1).Count());
}
catch (ArgumentOutOfRangeException)
{
Console.WriteLine("ArgumentOutOfRangeException");
}
Console.WriteLine(k > n ? 0 : Enumerable.Range(0, n - k + 1).Count());
ArgumentOutOfRangeException
0
- Go bit masks do not give the lexicographic order. A loop over the masks from 0 to 2^n - 1 that keeps the masks with k ones gives all the choices, but
[2 3](mask 6) comes before[1 4](mask 9). Also, there is no limit on the shift count: "Shifts behave as if the left operand is shifted n times by 1 for a shift count of n."6 Thusuint64(1) << 64is 0, and the loop runs zero times for 64 items:
package main
import (
"fmt"
"math/bits"
)
func main() {
items := []int{1, 2, 3, 4}
var picks [][]int
for mask := uint(0); mask < 1<<len(items); mask++ {
if bits.OnesCount(mask) != 2 {
continue
}
var pick []int
for i, x := range items {
if mask&(1<<i) != 0 {
pick = append(pick, x)
}
}
picks = append(picks, pick)
}
fmt.Println(picks)
var n uint = 64
fmt.Println(uint64(1) << n)
}
[[1 2] [1 3] [2 3] [1 4] [2 4] [3 4]]
0
- Rust windows are not combinations.
windows(2)"Returns an iterator over all contiguous windows of length size. The windows overlap."7 Thus it gives only the 3 pairs of neighbours of 4 items, and not the 6 pairs:
fn main() {
let items = [1, 2, 3, 4];
let windows: Vec<_> = items.windows(2).collect();
println!("{} {:?}", windows.len(), windows);
let mut pairs = Vec::new();
for i in 0..items.len() {
for j in i + 1..items.len() {
pairs.push([items[i], items[j]]);
}
}
println!("{} {:?}", pairs.len(), pairs);
}
3 [[1, 2], [2, 3], [3, 4]]
6 [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
- C divide after you multiply. When both operands are integers, "the result is the algebraic quotient (not a fraction)"8, and the fraction part is lost.
c *= (n - i) / (i + 1)divides first, so 5 / 2 gives 2 and 4 / 3 gives 1.c = c * (n - i) / (i + 1)multiplies first, and then the division is exact. For C(6, 3), the first form gives 12, and the second gives the correct 20:
#include <stdio.h>
int main(void) {
int n = 6;
int k = 3;
int wrong = 1;
int right = 1;
for (int i = 0; i < k; i++) {
wrong *= (n - i) / (i + 1); // 6 / 1, then 5 / 2 is 2, then 4 / 3 is 1
right = right * (n - i) / (i + 1);
}
printf("%d %d\n", wrong, right);
return 0;
}
12 20
- C++ next_permutation on a mask gives the reverse order. A mask of zeros and then k ones, with
next_permutation, gives all the choices, but from the last to the first.prev_permutation"Permutes the target range [first, last) into the lexicographically previous permutation."9 Thus a mask of k ones and then zeros, withprev_permutation, gives the lexicographic order of the positions, as the solution does:
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
// pick returns the chosen positions of mask, for example "{0,3}".
static std::string pick(const std::vector<char> &mask) {
std::string s = "{";
for (std::size_t i = 0; i < mask.size(); i++) {
if (mask[i]) {
s += (s.size() > 1 ? "," : "") + std::to_string(i);
}
}
return s + "}";
}
int main() {
std::vector<char> up{0, 0, 1, 1};
std::string line;
do {
line += (line.empty() ? "" : " ") + pick(up);
} while (std::next_permutation(up.begin(), up.end()));
std::cout << line << '\n';
std::vector<char> down{1, 1, 0, 0};
line.clear();
do {
line += (line.empty() ? "" : " ") + pick(down);
} while (std::prev_permutation(down.begin(), down.end()));
std::cout << line << '\n';
}
{2,3} {1,3} {1,2} {0,3} {0,2} {0,1}
{0,1} {0,2} {0,3} {1,2} {1,3} {2,3}
- Bash arithmetic overflows with no error. "Evaluation is done in the largest fixed-width integers available, with no check for overflow"10. C(62, 31) is 465428353255261088, which fits in 64 bits. But from step 27 on, the product
c * (n - i)is more than the largest 64-bit integer, so the result is a wrong negative number. Use a tool with big integers, such asbc, when the counts can be large:
n=62
k=31
c=1
for ((i = 0; i < k; i++)); do
((c = c * (n - i) / (i + 1)))
done
echo "$c"
-284401161134521734
Related tasks
- Compute the permutations of a list: make each order of the items, where the order matters.
- Compute the Cartesian product: take one item from each of several lists.
- Remove duplicates from a list: remove equal items first to get each distinct choice once.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compute-the-combinations-of-a-list/.
import itertools
def combinations(items: list[int], k: int) -> list[list[int]]:
"""Return each choice of k items, in the lexicographic order of the positions."""
return [list(c) for c in itertools.combinations(items, k)]
test_combinations.py 24 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compute-the-combinations-of-a-list/.
import pytest
from combinations import combinations
CASES = {
"two-of-four": ([1, 2, 3, 4], 2, [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]),
"three-of-four": ([1, 2, 3, 4], 3, [[1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]]),
"zero-k": ([1, 2], 0, [[]]),
"empty": ([], 0, [[]]),
"k-too-large": ([1, 2], 3, []),
"all": ([1, 2, 3], 3, [[1, 2, 3]]),
"duplicates": ([1, 1, 2], 2, [[1, 1], [1, 2], [1, 2]]),
"unsorted": ([3, 1, 2], 2, [[3, 1], [3, 2], [1, 2]]),
"extremes": ([-2147483648, 2147483647], 1, [[-2147483648], [2147483647]]),
}
@pytest.mark.parametrize("name", CASES)
def test_combinations(name):
items, k, want = CASES[name]
assert combinations(items, k) == want
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-combinations-of-a-list/.
#include "combinations.hpp"
#include <algorithm>
std::vector<std::vector<std::int32_t>> combinations(const std::vector<std::int32_t> &items, std::size_t k) {
std::vector<std::vector<std::int32_t>> out;
if (k > items.size()) {
return out;
}
// mask marks the chosen positions: k ones, then zeros. prev_permutation
// goes from 1100 to 1010 and on to 0011, so the chosen positions come in
// lexicographic order.
std::vector<char> mask(items.size(), 0);
std::fill_n(mask.begin(), k, char{1});
do {
std::vector<std::int32_t> pick;
pick.reserve(k);
for (std::size_t i = 0; i < items.size(); i++) {
if (mask[i]) {
pick.push_back(items[i]);
}
}
out.push_back(std::move(pick));
} while (std::prev_permutation(mask.begin(), mask.end()));
return out;
}
combinations.hpp 12 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-combinations-of-a-list/.
#pragma once
#include <cstddef>
#include <cstdint>
#include <vector>
// combinations returns each choice of k items, in the lexicographic order of
// the positions.
std::vector<std::vector<std::int32_t>> combinations(const std::vector<std::int32_t> &items, std::size_t k);
test_combinations.cpp 38 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-combinations-of-a-list/.
#include "combinations.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, std::size_t k, const Lists &want) {
if (combinations(items, k) != want) {
std::cerr << "case " << name << " failed\n";
failures++;
}
}
int main() {
check("two-of-four", List{1, 2, 3, 4}, 2, Lists{{1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 4}, {3, 4}});
check("three-of-four", List{1, 2, 3, 4}, 3, Lists{{1, 2, 3}, {1, 2, 4}, {1, 3, 4}, {2, 3, 4}});
check("zero-k", List{1, 2}, 0, Lists{List{}});
check("empty", List{}, 0, Lists{List{}});
check("k-too-large", List{1, 2}, 3, Lists{});
check("all", List{1, 2, 3}, 3, Lists{{1, 2, 3}});
check("duplicates", List{1, 1, 2}, 2, Lists{{1, 1}, {1, 2}, {1, 2}});
check("unsorted", List{3, 1, 2}, 2, Lists{{3, 1}, {3, 2}, {1, 2}});
check("extremes", List{INT32_MIN, INT32_MAX}, 1, Lists{{INT32_MIN}, {INT32_MAX}});
if (failures > 0) {
return 1;
}
std::cout << "all cases pass\n";
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-combinations-of-a-list/.
import java.util.ArrayList;
import java.util.List;
final class Combinations {
private Combinations() {}
/** Returns each choice of k items, in the lexicographic order of the positions. */
static int[][] combinations(int[] items, int k) {
List<int[]> out = new ArrayList<>();
if (k <= items.length) {
visit(items, new int[k], 0, 0, out);
}
return out.toArray(new int[0][]);
}
private static void visit(int[] items, int[] path, int depth, int start, List<int[]> out) {
if (depth == path.length) {
// path changes later, so add a copy.
out.add(path.clone());
return;
}
// Stop when too few items are left to fill path.
for (int i = start; i <= items.length - (path.length - depth); i++) {
path[depth] = items[i];
visit(items, path, depth + 1, i + 1, out);
}
}
}
CombinationsTest.java 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-combinations-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 CombinationsTest {
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("two-of-four", new int[] {1, 2, 3, 4}, 2, new int[][] {{1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 4}, {3, 4}}),
Arguments.of("three-of-four", new int[] {1, 2, 3, 4}, 3, new int[][] {{1, 2, 3}, {1, 2, 4}, {1, 3, 4}, {2, 3, 4}}),
Arguments.of("zero-k", new int[] {1, 2}, 0, new int[][] {{}}),
Arguments.of("empty", new int[] {}, 0, new int[][] {{}}),
Arguments.of("k-too-large", new int[] {1, 2}, 3, new int[][] {}),
Arguments.of("all", new int[] {1, 2, 3}, 3, new int[][] {{1, 2, 3}}),
Arguments.of("duplicates", new int[] {1, 1, 2}, 2, new int[][] {{1, 1}, {1, 2}, {1, 2}}),
Arguments.of("unsorted", new int[] {3, 1, 2}, 2, new int[][] {{3, 1}, {3, 2}, {1, 2}}),
Arguments.of("extremes", new int[] {Integer.MIN_VALUE, Integer.MAX_VALUE}, 1, new int[][] {{Integer.MIN_VALUE}, {Integer.MAX_VALUE}}));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void combinations(String name, int[] items, int k, int[][] want) {
assertArrayEquals(want, Combinations.combinations(items, k), name);
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-combinations-of-a-list/.
#include "combinations.h"
int combinations(const int32_t *items, size_t n, size_t k, int32_t *out, size_t cap, size_t *count) {
if (n > COMBINATIONS_MAX) {
return -1;
}
if (k > n) {
*count = 0;
return 0;
}
// After step i, total is C(n, i + 1). Multiply first, then divide: the
// division is exact, and a division first would truncate.
size_t total = 1;
for (size_t i = 0; i < k; i++) {
if (total > SIZE_MAX / (n - i)) {
return -1;
}
total = total * (n - i) / (i + 1);
}
if (k > 0 && total > cap / k) {
return -1;
}
// idx holds the chosen positions in increasing order, from 0, 1, ...
// to n - k, ..., n - 1.
size_t idx[COMBINATIONS_MAX];
for (size_t j = 0; j < k; j++) {
idx[j] = j;
}
size_t r = 0;
for (;;) {
for (size_t j = 0; j < k; j++) {
out[r * k + j] = items[idx[j]];
}
r++;
// Find the last position that can move right.
size_t i = k;
while (i > 0 && idx[i - 1] == n - k + i - 1) {
i--;
}
if (i == 0) {
break;
}
idx[i - 1]++;
for (size_t j = i; j < k; j++) {
idx[j] = idx[j - 1] + 1;
}
}
*count = total;
return 0;
}
combinations.h 22 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-combinations-of-a-list/.
#ifndef COMBINATIONS_H
#define COMBINATIONS_H
#include <stddef.h>
#include <stdint.h>
// COMBINATIONS_MAX is the largest n.
#define COMBINATIONS_MAX 32
// combinations writes each choice of k of the n items to out, in the
// lexicographic order of the positions. Choice r is at out[r * k] to
// out[r * k + k - 1]. It stores the number of choices, C(n, k), in *count and
// returns 0. k = 0 gives one empty choice, and k > n gives no choices. It
// returns -1 when n > COMBINATIONS_MAX, when C(n, k) does not fit in a
// size_t, or when out has room for fewer than C(n, k) * k items. Then it
// writes nothing.
int combinations(const int32_t *items, size_t n, size_t k, int32_t *out, size_t cap, size_t *count);
#endif
test_combinations.c 62 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-combinations-of-a-list/.
#include "combinations.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 choices, C choices.
#define CHECK(name, n, given, k, 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 = combinations(g, n, k, 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("two-of-four", 4, L(1, 2, 3, 4), 2, 12, 6, L(1, 2, 1, 3, 1, 4, 2, 3, 2, 4, 3, 4));
CHECK("three-of-four", 4, L(1, 2, 3, 4), 3, 12, 4, L(1, 2, 3, 1, 2, 4, 1, 3, 4, 2, 3, 4));
CHECK("zero-k", 2, L(1, 2), 0, 0, 1, L(0));
CHECK("empty", 0, L(0), 0, 0, 1, L(0));
CHECK("k-too-large", 2, L(1, 2), 3, 0, 0, L(0));
CHECK("all", 3, L(1, 2, 3), 3, 3, 1, L(1, 2, 3));
CHECK("duplicates", 3, L(1, 1, 2), 2, 6, 3, L(1, 1, 1, 2, 1, 2));
CHECK("unsorted", 3, L(3, 1, 2), 2, 6, 3, L(3, 1, 3, 2, 1, 2));
CHECK("extremes", 2, L(INT32_MIN, INT32_MAX), 1, 2, 2, L(INT32_MIN, INT32_MAX));
// out has room for 5 items, and the 3 choices of 2 need 6.
const int32_t three[] = {1, 2, 3};
int32_t small[5] = {0, 0, 0, 0, 0};
size_t count = 0;
if (combinations(three, 3, 2, small, 5, &count) != -1 || small[0] != 0) {
fprintf(stderr, "case small failed\n");
failures++;
}
// 33 items are more than COMBINATIONS_MAX.
const int32_t many[33] = {0};
if (combinations(many, 33, 1, small, 5, &count) != -1) {
fprintf(stderr, "case max failed\n");
failures++;
}
if (failures > 0) {
return 1;
}
printf("all cases pass\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-combinations-of-a-list/.
using System.Collections.Generic;
public static class Combinations
{
// Of returns each choice of k items, in the lexicographic order of the positions.
public static int[][] Of(int[] items, int k)
{
var output = new List<int[]>();
if (k <= items.Length)
{
Visit(items, new int[k], 0, 0, output);
}
return output.ToArray();
}
private static void Visit(int[] items, int[] path, int depth, int start, List<int[]> output)
{
if (depth == path.Length)
{
// path changes later, so add a copy.
output.Add((int[])path.Clone());
return;
}
// Stop when too few items are left to fill path.
for (int i = start; i <= items.Length - (path.Length - depth); i++)
{
path[depth] = items[i];
Visit(items, path, depth + 1, i + 1, output);
}
}
}
CombinationsTests.cs 28 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-combinations-of-a-list/.
using Xunit;
public sealed class CombinationsTests
{
public static TheoryData<string, int[], int, int[][]> Cases => new()
{
{ "two-of-four", new[] { 1, 2, 3, 4 }, 2, new[] { new[] { 1, 2 }, new[] { 1, 3 }, new[] { 1, 4 }, new[] { 2, 3 }, new[] { 2, 4 }, new[] { 3, 4 } } },
{ "three-of-four", new[] { 1, 2, 3, 4 }, 3, new[] { new[] { 1, 2, 3 }, new[] { 1, 2, 4 }, new[] { 1, 3, 4 }, new[] { 2, 3, 4 } } },
{ "zero-k", new[] { 1, 2 }, 0, new[] { new int[0] } },
{ "empty", new int[0], 0, new[] { new int[0] } },
{ "k-too-large", new[] { 1, 2 }, 3, new int[0][] },
{ "all", new[] { 1, 2, 3 }, 3, new[] { new[] { 1, 2, 3 } } },
{ "duplicates", new[] { 1, 1, 2 }, 2, new[] { new[] { 1, 1 }, new[] { 1, 2 }, new[] { 1, 2 } } },
{ "unsorted", new[] { 3, 1, 2 }, 2, new[] { new[] { 3, 1 }, new[] { 3, 2 }, new[] { 1, 2 } } },
{ "extremes", new[] { int.MinValue, int.MaxValue }, 1, new[] { new[] { int.MinValue }, new[] { int.MaxValue } } },
};
[Theory]
[MemberData(nameof(Cases))]
public void Check(string name, int[] items, int k, int[][] want)
{
Assert.NotNull(name);
Assert.Equal(want, Combinations.Of(items, k));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-combinations-of-a-list/.
/**
* @param {number[]} items
* @param {number} k
* @returns {number[][]}
*/
export function combinations(items, k) {
const out = [];
const path = [];
// visit adds each item from position start on to path in turn. It stops
// when too few items are left to fill path.
const visit = (start) => {
if (path.length === k) {
out.push([...path]);
return;
}
for (let i = start; i <= items.length - (k - path.length); i++) {
path.push(items[i]);
visit(i + 1);
path.pop();
}
};
visit(0);
return out;
}
combinations.test.js 25 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-combinations-of-a-list/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { combinations } from "./combinations.js";
const cases = [
["two-of-four", [1, 2, 3, 4], 2, [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]],
["three-of-four", [1, 2, 3, 4], 3, [[1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]]],
["zero-k", [1, 2], 0, [[]]],
["empty", [], 0, [[]]],
["k-too-large", [1, 2], 3, []],
["all", [1, 2, 3], 3, [[1, 2, 3]]],
["duplicates", [1, 1, 2], 2, [[1, 1], [1, 2], [1, 2]]],
["unsorted", [3, 1, 2], 2, [[3, 1], [3, 2], [1, 2]]],
["extremes", [-2147483648, 2147483647], 1, [[-2147483648], [2147483647]]],
];
for (const [name, items, k, want] of cases) {
test(name, () => {
assert.deepEqual(combinations(items, k), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-combinations-of-a-list/.
export function combinations(items: readonly number[], k: number): number[][] {
const out: number[][] = [];
const path: number[] = [];
// visit adds each item from position start on to path in turn. It stops
// when too few items are left to fill path.
const visit = (start: number): void => {
if (path.length === k) {
out.push([...path]);
return;
}
for (let i = start; i <= items.length - (k - path.length); i++) {
path.push(items[i]);
visit(i + 1);
path.pop();
}
};
visit(0);
return out;
}
combinations.test.ts 25 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-combinations-of-a-list/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { combinations } from "./combinations.ts";
const cases: [string, number[], number, number[][]][] = [
["two-of-four", [1, 2, 3, 4], 2, [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]],
["three-of-four", [1, 2, 3, 4], 3, [[1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]]],
["zero-k", [1, 2], 0, [[]]],
["empty", [], 0, [[]]],
["k-too-large", [1, 2], 3, []],
["all", [1, 2, 3], 3, [[1, 2, 3]]],
["duplicates", [1, 1, 2], 2, [[1, 1], [1, 2], [1, 2]]],
["unsorted", [3, 1, 2], 2, [[3, 1], [3, 2], [1, 2]]],
["extremes", [-2147483648, 2147483647], 1, [[-2147483648], [2147483647]]],
];
for (const [name, items, k, want] of cases) {
test(name, () => {
assert.deepEqual(combinations(items, k), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-combinations-of-a-list/.
// Package combinations computes all the choices of k items of a list.
package combinations
import "slices"
// Combinations returns each choice of k items, in the lexicographic order of
// the positions. Each choice has its own array.
func Combinations(items []int32, k int) [][]int32 {
var out [][]int32
if k > len(items) {
return out
}
path := make([]int32, 0, k)
var visit func(start int)
visit = func(start int) {
if len(path) == k {
// path changes later, so add a copy.
out = append(out, slices.Clone(path))
return
}
// Stop when too few items are left to fill path.
for i := start; i <= len(items)-(k-len(path)); i++ {
path = append(path, items[i])
visit(i + 1)
path = path[:len(path)-1]
}
}
visit(0)
return out
}
combinations_test.go 44 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-combinations-of-a-list/.
package combinations
import (
"math"
"slices"
"testing"
)
var cases = []struct {
name string
items []int32
k int
want [][]int32
}{
{"two-of-four", []int32{1, 2, 3, 4}, 2, [][]int32{{1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 4}, {3, 4}}},
{"three-of-four", []int32{1, 2, 3, 4}, 3, [][]int32{{1, 2, 3}, {1, 2, 4}, {1, 3, 4}, {2, 3, 4}}},
{"zero-k", []int32{1, 2}, 0, [][]int32{{}}},
{"empty", []int32{}, 0, [][]int32{{}}},
{"k-too-large", []int32{1, 2}, 3, [][]int32{}},
{"all", []int32{1, 2, 3}, 3, [][]int32{{1, 2, 3}}},
{"duplicates", []int32{1, 1, 2}, 2, [][]int32{{1, 1}, {1, 2}, {1, 2}}},
{"unsorted", []int32{3, 1, 2}, 2, [][]int32{{3, 1}, {3, 2}, {1, 2}}},
{"extremes", []int32{math.MinInt32, math.MaxInt32}, 1, [][]int32{{math.MinInt32}, {math.MaxInt32}}},
}
func TestCombinations(t *testing.T) {
for _, c := range cases {
got := Combinations(c.items, c.k)
if !slices.EqualFunc(got, c.want, slices.Equal[[]int32]) {
t.Errorf("%s: got %v, want %v", c.name, got, c.want)
}
}
}
func TestCombinationsOwnArrays(t *testing.T) {
got := Combinations([]int32{1, 2, 3}, 2)
got[0][0] = 99
if got[1][0] != 1 {
t.Errorf("a change to one choice changed another: %v", got)
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-combinations-of-a-list/.
/// Returns each choice of k items, in the lexicographic order of the positions.
pub fn combinations(items: &[i32], k: usize) -> Vec<Vec<i32>> {
let mut out = Vec::new();
if k <= items.len() {
let mut path = Vec::with_capacity(k);
visit(items, k, 0, &mut path, &mut out);
}
out
}
fn visit(items: &[i32], k: usize, start: usize, path: &mut Vec<i32>, out: &mut Vec<Vec<i32>>) {
if path.len() == k {
// path changes later, so add a copy.
out.push(path.clone());
return;
}
// Stop when too few items are left to fill path.
for i in start..=items.len() - (k - path.len()) {
path.push(items[i]);
visit(items, k, i + 1, path, out);
path.pop();
}
}
tests/combinations_test.rs 22 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-combinations-of-a-list/.
use algo_compute_the_combinations_of_a_list::combinations;
#[test]
fn cases() {
let cases: Vec<(&str, Vec<i32>, usize, Vec<Vec<i32>>)> = vec![
("two-of-four", vec![1, 2, 3, 4], 2, vec![vec![1, 2], vec![1, 3], vec![1, 4], vec![2, 3], vec![2, 4], vec![3, 4]]),
("three-of-four", vec![1, 2, 3, 4], 3, vec![vec![1, 2, 3], vec![1, 2, 4], vec![1, 3, 4], vec![2, 3, 4]]),
("zero-k", vec![1, 2], 0, vec![Vec::new()]),
("empty", Vec::new(), 0, vec![Vec::new()]),
("k-too-large", vec![1, 2], 3, Vec::new()),
("all", vec![1, 2, 3], 3, vec![vec![1, 2, 3]]),
("duplicates", vec![1, 1, 2], 2, vec![vec![1, 1], vec![1, 2], vec![1, 2]]),
("unsorted", vec![3, 1, 2], 2, vec![vec![3, 1], vec![3, 2], vec![1, 2]]),
("extremes", vec![i32::MIN, i32::MAX], 1, vec![vec![i32::MIN], vec![i32::MAX]]),
];
for (name, items, k, want) in cases {
assert_eq!(combinations(&items, k), want, "{name}");
}
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compute-the-combinations-of-a-list/.
# combinations K ITEM...
# Prints each choice of K items on one line, with the items separated by
# spaces, in the lexicographic order of the positions. K = 0 prints one empty
# line, the one empty choice. K more than the number of items prints nothing.
combinations() {
local k=$1
shift
_combinations_visit "$k" "" "$@"
}
# _combinations_visit K PREFIX ITEM...
# Prints PREFIX followed by each choice of K of the items.
_combinations_visit() {
# local keeps the variables of each call apart in the recursion.
local k=$1 prefix=$2 i
shift 2
if ((k == 0)); then
printf '%s\n' "$prefix"
return
fi
local -a rest=("$@")
# Stop when too few items are left to fill the choice.
for ((i = 0; i + k <= ${#rest[@]}; i++)); do
_combinations_visit "$((k - 1))" "${prefix:+$prefix }${rest[i]}" "${rest[@]:i+1}"
done
}
test_combinations.bats 29 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compute-the-combinations-of-a-list/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/combinations.sh"
}
check() { # check WANT K 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=$(combinations "$@"; printf x)
[ "$got" = "$want" ] || { printf 'got: %q\nwant: %q\n' "$got" "$want"; return 1; }
}
@test "two-of-four" { check "1 2\n1 3\n1 4\n2 3\n2 4\n3 4\n" 2 1 2 3 4; }
@test "three-of-four" { check "1 2 3\n1 2 4\n1 3 4\n2 3 4\n" 3 1 2 3 4; }
@test "zero-k" { check "\n" 0 1 2; }
@test "empty" { check "\n" 0; }
@test "k-too-large" { check "" 3 1 2; }
@test "all" { check "1 2 3\n" 3 1 2 3; }
@test "duplicates" { check "1 1\n1 2\n1 2\n" 2 1 1 2; }
@test "unsorted" { check "3 1\n3 2\n1 2\n" 2 3 1 2; }
@test "extremes" { check "-2147483648\n2147483647\n" 1 -2147483648 2147483647; }
References
- The Python Standard Library, itertools, itertools.combinations(); itertools.combinations_with_replacement()
- The Python Standard Library, math, Number-theoretic functions
- MDN Web Docs, Array.prototype.fill(), Parameters
- Java SE 25 API, Class Math, multiplyExact(long, int)
- .NET API reference, Enumerable.Range(Int32, Int32) Method, Exceptions
- The Go Programming Language Specification, Integer operators
- Rust standard library, primitive type slice, windows
- cppreference.com, Arithmetic operators (C), Division
- cppreference.com, std::prev_permutation, Description
- Bash Reference Manual, 6.5 Shell Arithmetic
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag MXGKYK Edit this page History Report an error Markdown