Programming Search⌘K

Taskcore

Compute the Cartesian product

Also called cartesian product, cross product of lists, all pairs of two lists, all combinations of one item from each list, nested loops over lists, itertools.product.

Make each tuple that takes one item from each of several lists of integers, in the order of nested loops.

Task

Make each tuple that takes one item from each of several lists of integers. The function cartesian_product(lists) returns the tuples in the order of nested loops: the first list is the outer loop, and the last list is the inner loop. For example, cartesian_product([[1, 2], [3, 4]]) is [[1, 3], [1, 4], [2, 3], [2, 4]].

The number of tuples is the product of the lengths of the lists. Thus the product of no lists is one empty tuple, [[]], and a product with an empty list has no tuples. The items are 32-bit signed integers. The product of the lengths is at most 100000.

Solutions

Language Add the items of each list to each tuple
Python [list(t) for t in product(*lists)]
JavaScript, TypeScript reduce from [[]], with flatMap over the tuples and map over the items
Java a loop over the lists, with Arrays.copyOf for each new tuple
C# SelectMany over the tuples, once for each list
Go a loop over the lists, with make and copy for each new tuple
Rust fold from vec![Vec::new()], with flat_map over the tuples
C the digits of each row number, with the last list as the lowest digit
C++ a loop over the lists, with reserve and push_back
Bash a loop over the arguments, with read -r -a for the items of each list
  • Nested loops. product is "Roughly equivalent to nested for-loops in a generator expression. For example, product(A, B) returns the same as ((x,y) for x in A for y in B)."1 It also says: "The nested loops cycle like an odometer with the rightmost element advancing on every iteration."1 The other solutions do the same with one loop for each list, so the number of lists can change at run time.
  • Sorted input gives sorted output. "This pattern creates a lexicographic ordering so that if the input’s iterables are sorted, the product tuples are emitted in sorted order."1
  • The size grows fast. Each list multiplies the number of tuples by its length. Ten lists of ten items give 10,000,000,000 tuples. product also reads all its input first: "Before product() runs, it completely consumes the input iterables, keeping pools of values in memory to generate the products."1
  • C. The caller gives the array out and its capacity in items. Tuple r is at out[r * n] to out[r * n + n - 1]. The function returns -1 when the tuples do not fit, and then it writes nothing. It finds the item of list k from the digits of r, so it needs no more memory.
  • Bash. Each argument is one list, with the items separated by spaces. The function prints each tuple on one line.

Edge cases

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

  • no-lists: no lists give one empty tuple, [[]]. Python agrees: list(product()) is [()]. A solution that starts with no tuples, and not with one empty tuple, gives [] for all the inputs.
  • one-empty: [[1, 2], []] gives no tuples, because there is no item to take from the empty list.
  • single: one list gives a tuple of one item for each item.
  • duplicates: [[1, 1], [2]] gives [[1, 2], [1, 2]]. The function does not remove equal tuples.
  • negative and extremes: negative items, -2147483648 and 2147483647 stay as they are.

Pitfalls

  • Python product needs the star. product(*lists) gives each list as one argument. product(lists) gives the product of one list, so each tuple has one item, which is an inner list. product() with no arguments gives one empty tuple:
from itertools import product

lists = [[1, 2], [3, 4]]
print(list(product(*lists)))
print(list(product(lists)))
print(list(product()))
Output
[(1, 3), (1, 4), (2, 3), (2, 4)]
[([1, 2],), ([3, 4],)]
[()]
  • JavaScript map gives nested arrays. With map on the outer list, each item of a gives one array of pairs. flatMap "returns a new array formed by applying a given callback function to each element of the array, and then flattening the result by one level."2 Thus it gives one flat array of pairs:
const a = [1, 2];
const b = [3, 4];
console.log(JSON.stringify(a.map((x) => b.map((y) => [x, y]))));
console.log(JSON.stringify(a.flatMap((x) => b.map((y) => [x, y]))));
Output
[[[1,3],[1,4]],[[2,3],[2,4]]]
[[1,3],[1,4],[2,3],[2,4]]
  • Java a stream can be used only once. "A stream should be operated on (invoking an intermediate or terminal stream operation) only once."3 Also, "A stream implementation may throw IllegalStateException if it detects that the stream is being reused."3 In the example, the inner stream bs is made once, outside flatMap, so the second item of a uses it again. Make a new inner stream for each outer item:
import java.util.List;
import java.util.stream.Stream;

public class Main {
  public static void main(String[] args) {
    List<Integer> a = List.of(1, 2);
    List<Integer> b = List.of(3, 4);
    System.out.println(a.stream().flatMap(x -> b.stream().map(y -> x * 10 + y)).toList());
    Stream<Integer> bs = b.stream();
    try {
      System.out.println(a.stream().flatMap(x -> bs.map(y -> x * 10 + y)).toList());
    } catch (IllegalStateException e) {
      System.out.println(e.getClass().getSimpleName());
    }
  }
}
Output
[13, 14, 23, 24]
IllegalStateException
  • C# SelectMany runs later. "This method is implemented by using deferred execution."4 Also, "The query represented by this method is not executed until the object is enumerated"4. In the example, later reads b when Join enumerates it, after b.Add(5), so it has the pairs with 5. ToArray runs the query at once:
using System;
using System.Collections.Generic;
using System.Linq;

var a = new List<int> { 1, 2 };
var b = new List<int> { 3, 4 };
var later = a.SelectMany(x => b, (x, y) => x * 10 + y);
var now = a.SelectMany(x => b, (x, y) => x * 10 + y).ToArray();
b.Add(5);
Console.WriteLine(string.Join(" ", later));
Console.WriteLine(string.Join(" ", now));
Output
13 14 15 23 24 25
13 14 23 24
  • Go the count of tuples can wrap around. "For signed integers, the operations +, -, *, /, and << may legally overflow and the resulting value exists and is deterministically defined by the signed integer representation, the operation, and its operands. Overflow does not cause a run-time panic."5 In the example, on a 64-bit platform, 2^32 times 2^32 is 0. Thus a size from the product of the lengths can be wrong with no error. Compare with math.MaxInt divided by the length:
package main

import (
	"fmt"
	"math"
)

func main() {
	n := 1 << 32
	fmt.Println(n * n)
	fmt.Println(n > math.MaxInt/n)
}
Output
0
true
  • Rust fold from an empty vector gives nothing. For fold, "The initial value is the value the accumulator will have on the first call."6 An empty vector has no tuple to extend, so each step gives an empty vector again. Start from one empty tuple:
fn main() {
    let lists: Vec<Vec<i32>> = vec![vec![1, 2], vec![3]];
    let step = |acc: Vec<Vec<i32>>, xs: &Vec<i32>| -> Vec<Vec<i32>> {
        acc.iter()
            .flat_map(|t| xs.iter().map(move |&x| [t.clone(), vec![x]].concat()))
            .collect()
    };
    let wrong = lists.iter().fold(Vec::new(), step);
    let right = lists.iter().fold(vec![Vec::new()], step);
    println!("{wrong:?}");
    println!("{right:?}");
}
Output
[]
[[1, 3], [2, 3]]
  • C the product of the lengths can wrap around. "Unsigned integer arithmetic is always performed modulo 2n where n is the number of bits in that particular integer."7 In the example, with a 64-bit size_t, 2^32 times 2^32 is 0, so a buffer of that size is too small. Compare with SIZE_MAX divided by the length before you multiply, as the solution does:
#include <stdint.h>
#include <stdio.h>

int main(void) {
    size_t a = (size_t)1 << 32;
    size_t b = (size_t)1 << 32;
    // The product wraps around to 0.
    printf("%zu\n", a * b);
    // This test does not wrap around: 1 means that a * b does not fit.
    printf("%d\n", a > SIZE_MAX / b);
    return 0;
}
Output
0
1
  • C++ reserve does not check the product. reserve throws "std::length_error if new_cap > max_size()."8 But a product that wraps around is a small number. In the example, reserve(a * a) gets 0 and does not fail. Only a count that is too large gives the error:
#include <cstddef>
#include <iostream>
#include <limits>
#include <stdexcept>
#include <vector>

int main() {
    std::vector<std::vector<int>> out;
    std::size_t a = std::size_t{1} << 32;
    // a * a wraps around to 0, so reserve gets 0 and does not fail.
    out.reserve(a * a);
    std::cout << out.capacity() << '\n';
    try {
        out.reserve(std::numeric_limits<std::size_t>::max());
    } catch (const std::length_error &) {
        std::cout << "length_error\n";
    }
}
Output
0
length_error
  • Bash brace expansion does not read variables. Brace expansion makes a product of words: {1,2}{a,b} gives four words. But "Brace expansion is performed before any other expansions"9, so {$x} has no comma when Bash expands the braces. Then $x expands, and the braces stay in the words. Use loops for lists in variables, as the solution does:
echo {1,2}{a,b}
x="1,2"
echo {$x}{a,b}
Output
1a 1b 2a 2b
{1,2}a {1,2}b

Code

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

cartesian_product.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compute-the-cartesian-product/.

from itertools import product


def cartesian_product(lists: list[list[int]]) -> list[list[int]]:
    """Return each tuple that takes one item from each list, as a list, in nested-loop order."""
    # The star passes each inner list as one argument.
    return [list(t) for t in product(*lists)]
test_cartesian_product.py 23 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compute-the-cartesian-product/.

import pytest

from cartesian_product import cartesian_product

CASES = {
    "two": ([[1, 2], [3, 4]], [[1, 3], [1, 4], [2, 3], [2, 4]]),
    "three": ([[1, 2], [3], [4, 5]], [[1, 3, 4], [1, 3, 5], [2, 3, 4], [2, 3, 5]]),
    "no-lists": ([], [[]]),
    "one-empty": ([[1, 2], []], []),
    "single": ([[7, 8, 9]], [[7], [8], [9]]),
    "duplicates": ([[1, 1], [2]], [[1, 2], [1, 2]]),
    "negative": ([[-1], [-2, -3]], [[-1, -2], [-1, -3]]),
    "extremes": ([[-2147483648, 2147483647], [0]], [[-2147483648, 0], [2147483647, 0]]),
}


@pytest.mark.parametrize("name", CASES)
def test_cartesian_product(name):
    lists, want = CASES[name]
    assert cartesian_product(lists) == want
cartesian_product.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-cartesian-product/.

#include "cartesian_product.hpp"

std::vector<std::vector<std::int32_t>> cartesian_product(const std::vector<std::vector<std::int32_t>> &lists) {
    // The product of no lists is one empty tuple.
    std::vector<std::vector<std::int32_t>> tuples{{}};
    for (const auto &xs : lists) {
        std::vector<std::vector<std::int32_t>> next;
        next.reserve(tuples.size() * xs.size());
        for (const auto &t : tuples) {
            for (std::int32_t x : xs) {
                auto u = t;
                u.push_back(x);
                next.push_back(std::move(u));
            }
        }
        tuples = std::move(next);
    }
    return tuples;
}
cartesian_product.hpp 11 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-cartesian-product/.

#pragma once

#include <cstdint>
#include <vector>

// cartesian_product returns each tuple that takes one item from each vector,
// in nested-loop order.
std::vector<std::vector<std::int32_t>> cartesian_product(const std::vector<std::vector<std::int32_t>> &lists);
test_cartesian_product.cpp 37 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-cartesian-product/.

#include "cartesian_product.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 Lists &lists, const Lists &want) {
    if (cartesian_product(lists) != want) {
        std::cerr << "case " << name << " failed\n";
        failures++;
    }
}

int main() {
    check("two", Lists{{1, 2}, {3, 4}}, Lists{{1, 3}, {1, 4}, {2, 3}, {2, 4}});
    check("three", Lists{{1, 2}, {3}, {4, 5}}, Lists{{1, 3, 4}, {1, 3, 5}, {2, 3, 4}, {2, 3, 5}});
    check("no-lists", Lists{}, Lists{List{}});
    check("one-empty", Lists{{1, 2}, {}}, Lists{});
    check("single", Lists{{7, 8, 9}}, Lists{{7}, {8}, {9}});
    check("duplicates", Lists{{1, 1}, {2}}, Lists{{1, 2}, {1, 2}});
    check("negative", Lists{{-1}, {-2, -3}}, Lists{{-1, -2}, {-1, -3}});
    check("extremes", Lists{{INT32_MIN, INT32_MAX}, {0}}, Lists{{INT32_MIN, 0}, {INT32_MAX, 0}});
    if (failures > 0) {
        return 1;
    }
    std::cout << "all cases pass\n";
    return 0;
}
CartesianProduct.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-cartesian-product/.

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

final class CartesianProduct {
  private CartesianProduct() {}

  /** Returns each tuple that takes one item from each array, in nested-loop order. */
  static int[][] cartesianProduct(int[][] lists) {
    List<int[]> tuples = new ArrayList<>();
    tuples.add(new int[0]);
    for (int[] xs : lists) {
      List<int[]> next = new ArrayList<>();
      for (int[] t : tuples) {
        for (int x : xs) {
          // A new array for each tuple, so that no two tuples share one.
          int[] u = Arrays.copyOf(t, t.length + 1);
          u[t.length] = x;
          next.add(u);
        }
      }
      tuples = next;
    }
    return tuples.toArray(new int[0][]);
  }
}
CartesianProductTest.java 29 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-cartesian-product/.

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 CartesianProductTest {
  static Stream<Arguments> cases() {
    return Stream.of(
        Arguments.of("two", new int[][] {{1, 2}, {3, 4}}, new int[][] {{1, 3}, {1, 4}, {2, 3}, {2, 4}}),
        Arguments.of("three", new int[][] {{1, 2}, {3}, {4, 5}}, new int[][] {{1, 3, 4}, {1, 3, 5}, {2, 3, 4}, {2, 3, 5}}),
        Arguments.of("no-lists", new int[][] {}, new int[][] {{}}),
        Arguments.of("one-empty", new int[][] {{1, 2}, {}}, new int[][] {}),
        Arguments.of("single", new int[][] {{7, 8, 9}}, new int[][] {{7}, {8}, {9}}),
        Arguments.of("duplicates", new int[][] {{1, 1}, {2}}, new int[][] {{1, 2}, {1, 2}}),
        Arguments.of("negative", new int[][] {{-1}, {-2, -3}}, new int[][] {{-1, -2}, {-1, -3}}),
        Arguments.of("extremes", new int[][] {{Integer.MIN_VALUE, Integer.MAX_VALUE}, {0}}, new int[][] {{Integer.MIN_VALUE, 0}, {Integer.MAX_VALUE, 0}}));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("cases")
  void cartesianProduct(String name, int[][] lists, int[][] want) {
    assertArrayEquals(want, CartesianProduct.cartesianProduct(lists), name);
  }
}
cartesian_product.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-cartesian-product/.

#include "cartesian_product.h"

#include <stdint.h>

int cartesian_product(const struct int_list *lists, size_t n, int32_t *out, size_t cap, size_t *count) {
    // The product of no lists is one empty tuple.
    size_t total = 1;
    for (size_t k = 0; k < n; k++) {
        if (lists[k].len == 0) {
            *count = 0;
            return 0;
        }
    }
    for (size_t k = 0; k < n; k++) {
        // total * len could wrap around, so compare with SIZE_MAX / len.
        if (total > SIZE_MAX / lists[k].len) {
            return -1;
        }
        total *= lists[k].len;
    }
    if (n > 0 && total > cap / n) {
        return -1;
    }
    for (size_t r = 0; r < total; r++) {
        // The digits of r, with the last list as the lowest digit, give the
        // index of the item in each list.
        size_t rest = r;
        for (size_t k = n; k-- > 0;) {
            out[r * n + k] = lists[k].items[rest % lists[k].len];
            rest /= lists[k].len;
        }
    }
    *count = total;
    return 0;
}
cartesian_product.h 23 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-cartesian-product/.

#ifndef CARTESIAN_PRODUCT_H
#define CARTESIAN_PRODUCT_H

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

// An int_list is len items at items. items can be NULL when len is 0.
struct int_list {
    const int32_t *items;
    size_t len;
};

// cartesian_product writes each tuple that takes one item from each of the n
// lists to out, in nested-loop order. Tuple r is at out[r * n] to
// out[r * n + n - 1]. It stores the number of tuples in *count and returns 0,
// or it returns -1 when out has room for fewer than count * n items. Then it
// writes nothing.
int cartesian_product(const struct int_list *lists, size_t n, int32_t *out, size_t cap, size_t *count);

#endif
test_cartesian_product.c 63 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-cartesian-product/.

#include "cartesian_product.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 of lists has {NULL, 0} in it, and
// an empty result has a 0 in it. N, M and C give the real lengths: N lists,
// M items in all the tuples, C tuples.
#define CHECK(name, n, given, m, c, flat)                                      \
    do {                                                                       \
        const struct int_list g[] = given;                                     \
        const int32_t want[] = flat;                                           \
        int32_t out[sizeof want / sizeof want[0]];                             \
        size_t count = 99;                                                     \
        int ok = cartesian_product(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("two", 2, L({(const int32_t[]){1, 2}, 2}, {(const int32_t[]){3, 4}, 2}), 8, 4, L(1, 3, 1, 4, 2, 3, 2, 4));
    CHECK("three", 3, L({(const int32_t[]){1, 2}, 2}, {(const int32_t[]){3}, 1}, {(const int32_t[]){4, 5}, 2}), 12, 4, L(1, 3, 4, 1, 3, 5, 2, 3, 4, 2, 3, 5));
    CHECK("no-lists", 0, L({NULL, 0}), 0, 1, L(0));
    CHECK("one-empty", 2, L({(const int32_t[]){1, 2}, 2}, {NULL, 0}), 0, 0, L(0));
    CHECK("single", 1, L({(const int32_t[]){7, 8, 9}, 3}), 3, 3, L(7, 8, 9));
    CHECK("duplicates", 2, L({(const int32_t[]){1, 1}, 2}, {(const int32_t[]){2}, 1}), 4, 2, L(1, 2, 1, 2));
    CHECK("negative", 2, L({(const int32_t[]){-1}, 1}, {(const int32_t[]){-2, -3}, 2}), 4, 2, L(-1, -2, -1, -3));
    CHECK("extremes", 2, L({(const int32_t[]){INT32_MIN, INT32_MAX}, 2}, {(const int32_t[]){0}, 1}), 4, 2, L(INT32_MIN, 0, INT32_MAX, 0));

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

    // The product of the lengths wraps around, so the function must give -1.
    const int32_t one[] = {1};
    const struct int_list huge[] = {{one, SIZE_MAX}, {one, 2}};
    if (cartesian_product(huge, 2, small, 3, &count) != -1) {
        fprintf(stderr, "case wrap failed\n");
        failures++;
    }

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

using System;
using System.Collections.Generic;
using System.Linq;

public static class CartesianProduct
{
    // Of returns each tuple that takes one item from each array, in nested-loop order.
    public static int[][] Of(int[][] lists)
    {
        IEnumerable<int[]> tuples = new[] { Array.Empty<int>() };
        foreach (int[] xs in lists)
        {
            // Each tuple t gives one new tuple for each item x of xs.
            tuples = tuples.SelectMany(t => xs, (t, x) => t.Append(x).ToArray());
        }
        return tuples.ToArray();
    }
}
CartesianProductTests.cs 27 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-cartesian-product/.

using Xunit;

public sealed class CartesianProductTests
{
    public static TheoryData<string, int[][], int[][]> Cases => new()
    {
        { "two", new[] { new[] { 1, 2 }, new[] { 3, 4 } }, new[] { new[] { 1, 3 }, new[] { 1, 4 }, new[] { 2, 3 }, new[] { 2, 4 } } },
        { "three", new[] { new[] { 1, 2 }, new[] { 3 }, new[] { 4, 5 } }, new[] { new[] { 1, 3, 4 }, new[] { 1, 3, 5 }, new[] { 2, 3, 4 }, new[] { 2, 3, 5 } } },
        { "no-lists", new int[0][], new[] { new int[0] } },
        { "one-empty", new[] { new[] { 1, 2 }, new int[0] }, new int[0][] },
        { "single", new[] { new[] { 7, 8, 9 } }, new[] { new[] { 7 }, new[] { 8 }, new[] { 9 } } },
        { "duplicates", new[] { new[] { 1, 1 }, new[] { 2 } }, new[] { new[] { 1, 2 }, new[] { 1, 2 } } },
        { "negative", new[] { new[] { -1 }, new[] { -2, -3 } }, new[] { new[] { -1, -2 }, new[] { -1, -3 } } },
        { "extremes", new[] { new[] { int.MinValue, int.MaxValue }, new[] { 0 } }, new[] { new[] { int.MinValue, 0 }, new[] { int.MaxValue, 0 } } },
    };

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

/**
 * @param {number[][]} lists
 * @returns {number[][]}
 */
export function cartesianProduct(lists) {
  // Start with one empty tuple, and add the items of each list in turn.
  return lists.reduce(
    (tuples, xs) => tuples.flatMap((t) => xs.map((x) => [...t, x])),
    [[]],
  );
}
cartesian_product.test.js 24 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-cartesian-product/.

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

import { cartesianProduct } from "./cartesian_product.js";

const cases = [
  ["two", [[1, 2], [3, 4]], [[1, 3], [1, 4], [2, 3], [2, 4]]],
  ["three", [[1, 2], [3], [4, 5]], [[1, 3, 4], [1, 3, 5], [2, 3, 4], [2, 3, 5]]],
  ["no-lists", [], [[]]],
  ["one-empty", [[1, 2], []], []],
  ["single", [[7, 8, 9]], [[7], [8], [9]]],
  ["duplicates", [[1, 1], [2]], [[1, 2], [1, 2]]],
  ["negative", [[-1], [-2, -3]], [[-1, -2], [-1, -3]]],
  ["extremes", [[-2147483648, 2147483647], [0]], [[-2147483648, 0], [2147483647, 0]]],
];

for (const [name, lists, want] of cases) {
  test(name, () => {
    assert.deepEqual(cartesianProduct(lists), want);
  });
}
cartesian_product.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-cartesian-product/.

export function cartesianProduct(lists: readonly (readonly number[])[]): number[][] {
  // Start with one empty tuple, and add the items of each list in turn.
  return lists.reduce<number[][]>(
    (tuples, xs) => tuples.flatMap((t) => xs.map((x) => [...t, x])),
    [[]],
  );
}
cartesian_product.test.ts 24 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-cartesian-product/.

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

import { cartesianProduct } from "./cartesian_product.ts";

const cases: [string, number[][], number[][]][] = [
  ["two", [[1, 2], [3, 4]], [[1, 3], [1, 4], [2, 3], [2, 4]]],
  ["three", [[1, 2], [3], [4, 5]], [[1, 3, 4], [1, 3, 5], [2, 3, 4], [2, 3, 5]]],
  ["no-lists", [], [[]]],
  ["one-empty", [[1, 2], []], []],
  ["single", [[7, 8, 9]], [[7], [8], [9]]],
  ["duplicates", [[1, 1], [2]], [[1, 2], [1, 2]]],
  ["negative", [[-1], [-2, -3]], [[-1, -2], [-1, -3]]],
  ["extremes", [[-2147483648, 2147483647], [0]], [[-2147483648, 0], [2147483647, 0]]],
];

for (const [name, lists, want] of cases) {
  test(name, () => {
    assert.deepEqual(cartesianProduct(lists), want);
  });
}
cartesian_product.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-cartesian-product/.

// Package cartesian computes the Cartesian product of lists.
package cartesian

// Product returns each tuple that takes one item from each slice, in
// nested-loop order. Each tuple has its own array.
func Product(lists [][]int32) [][]int32 {
	tuples := [][]int32{{}}
	for _, xs := range lists {
		next := make([][]int32, 0, len(tuples)*len(xs))
		for _, t := range tuples {
			for _, x := range xs {
				u := make([]int32, len(t)+1)
				copy(u, t)
				u[len(t)] = x
				next = append(next, u)
			}
		}
		tuples = next
	}
	return tuples
}
cartesian_product_test.go 42 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-cartesian-product/.

package cartesian

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

var cases = []struct {
	name  string
	lists [][]int32
	want  [][]int32
}{
	{"two", [][]int32{{1, 2}, {3, 4}}, [][]int32{{1, 3}, {1, 4}, {2, 3}, {2, 4}}},
	{"three", [][]int32{{1, 2}, {3}, {4, 5}}, [][]int32{{1, 3, 4}, {1, 3, 5}, {2, 3, 4}, {2, 3, 5}}},
	{"no-lists", [][]int32{}, [][]int32{{}}},
	{"one-empty", [][]int32{{1, 2}, {}}, [][]int32{}},
	{"single", [][]int32{{7, 8, 9}}, [][]int32{{7}, {8}, {9}}},
	{"duplicates", [][]int32{{1, 1}, {2}}, [][]int32{{1, 2}, {1, 2}}},
	{"negative", [][]int32{{-1}, {-2, -3}}, [][]int32{{-1, -2}, {-1, -3}}},
	{"extremes", [][]int32{{math.MinInt32, math.MaxInt32}, {0}}, [][]int32{{math.MinInt32, 0}, {math.MaxInt32, 0}}},
}

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

func TestProductOwnArrays(t *testing.T) {
	got := Product([][]int32{{1, 2}, {3, 4}})
	got[0][0] = 99
	if got[1][0] != 1 {
		t.Errorf("a change to one tuple changed another: %v", got)
	}
}
cartesian_product.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-cartesian-product/.

/// Returns each tuple that takes one item from each list, in nested-loop order.
pub fn cartesian_product(lists: &[Vec<i32>]) -> Vec<Vec<i32>> {
    // The product of no lists is one empty tuple, so the fold starts there.
    lists.iter().fold(vec![Vec::new()], |tuples, xs| {
        tuples
            .iter()
            .flat_map(|t| {
                xs.iter().map(move |&x| {
                    let mut u = t.clone();
                    u.push(x);
                    u
                })
            })
            .collect()
    })
}
tests/cartesian_product_test.rs 22 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-cartesian-product/.

use algo_compute_the_cartesian_product::cartesian_product;

#[test]
fn cases() {
    let none: Vec<Vec<i32>> = Vec::new();
    let cases: Vec<(&str, Vec<Vec<i32>>, Vec<Vec<i32>>)> = vec![
        ("two", vec![vec![1, 2], vec![3, 4]], vec![vec![1, 3], vec![1, 4], vec![2, 3], vec![2, 4]]),
        ("three", vec![vec![1, 2], vec![3], vec![4, 5]], vec![vec![1, 3, 4], vec![1, 3, 5], vec![2, 3, 4], vec![2, 3, 5]]),
        ("no-lists", none.clone(), vec![Vec::new()]),
        ("one-empty", vec![vec![1, 2], Vec::new()], none.clone()),
        ("single", vec![vec![7, 8, 9]], vec![vec![7], vec![8], vec![9]]),
        ("duplicates", vec![vec![1, 1], vec![2]], vec![vec![1, 2], vec![1, 2]]),
        ("negative", vec![vec![-1], vec![-2, -3]], vec![vec![-1, -2], vec![-1, -3]]),
        ("extremes", vec![vec![i32::MIN, i32::MAX], vec![0]], vec![vec![i32::MIN, 0], vec![i32::MAX, 0]]),
    ];
    for (name, lists, want) in cases {
        assert_eq!(cartesian_product(&lists), want, "{name}");
    }
}
cartesian_product.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compute-the-cartesian-product/.

# cartesian_product LIST...
# Each argument is one list, with the items separated by spaces. Prints each
# tuple that takes one item from each list on one line, with the items
# separated by spaces, in nested-loop order. With no arguments, it prints one
# empty line, the one empty tuple.
cartesian_product() {
  local list t x
  local -a items next tuples=("")
  for list in "$@"; do
    read -r -a items <<< "$list"
    next=()
    for t in "${tuples[@]}"; do
      for x in "${items[@]}"; do
        next+=("${t:+$t }$x")
      done
    done
    tuples=("${next[@]}")
  done
  if ((${#tuples[@]} > 0)); then
    printf '%s\n' "${tuples[@]}"
  fi
}
test_cartesian_product.bats 28 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compute-the-cartesian-product/.

bats_require_minimum_version 1.5.0

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

check() { # check WANT LIST...
  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=$(cartesian_product "$@"; printf x)
  [ "$got" = "$want" ] || { printf 'got:  %q\nwant: %q\n' "$got" "$want"; return 1; }
}

@test "two" { check "1 3\n1 4\n2 3\n2 4\n" "1 2" "3 4"; }
@test "three" { check "1 3 4\n1 3 5\n2 3 4\n2 3 5\n" "1 2" "3" "4 5"; }
@test "no-lists" { check "\n"; }
@test "one-empty" { check "" "1 2" ""; }
@test "single" { check "7\n8\n9\n" "7 8 9"; }
@test "duplicates" { check "1 2\n1 2\n" "1 1" "2"; }
@test "negative" { check "-1 -2\n-1 -3\n" "-1" "-2 -3"; }
@test "extremes" { check "-2147483648 0\n2147483647 0\n" "-2147483648 2147483647" "0"; }

References

  1. The Python Standard Library, itertools, itertools.product()
  2. MDN Web Docs, Array.prototype.flatMap(), Description
  3. Java SE 25 API, Interface Stream, Description
  4. .NET API reference, Enumerable.SelectMany method, Remarks
  5. The Go Programming Language Specification, Integer overflow
  6. Rust standard library, trait Iterator, fold
  7. cppreference.com, Arithmetic operators (C), Overflows
  8. cppreference.com, std::vector::reserve, Exceptions
  9. Bash Reference Manual, 3.5.1 Brace Expansion

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