cartesianProduct

inline fun <B> List<List<B>>.cartesianProduct(): List<List<B>>(source)

Returns every possible list that can be formed by choosing one element from each of the given lists in order; the "n-ary Cartesian product" of the lists. For example:

val cartesianProduct = listOf(listOf(1, 2), listOf("A", "B", "C")).cartesianProduct()

returns a list containing six lists in the following order:

  • [1, "A"]

  • [1, "B"]

  • [1, "C"]

  • [2, "A"]

  • [2, "B"]

  • [2, "C"]

The result is guaranteed to be in the "traditional", lexicographical order for Cartesian products that you would get from nesting for loops:

for (B b0 in lists.get(0)) {
for (B b1 in lists.get(1)) {
...
val tuple = listOf(b0, b1, ...)
// operate on tuple
}
}

Note that if any input list is empty, the Cartesian product will also be empty. If no lists at all are provided (an empty list), the resulting Cartesian product has one element, an empty list (counter-intuitive, but mathematically consistent).

Performance notes: while the cartesian product of lists of size m, n, p is a list of size m x n x p, its actual memory consumption is much smaller. When the cartesian product is constructed, the input lists are merely copied. Only as the resulting list is iterated are the individual lists created, and these are not retained after iteration.

Return

the Cartesian product, as an immutable list containing immutable lists

See also

Parameters

B

any common base class shared by all axes (often just Any)

Throws

if the size of the cartesian product would be greater than Integer.MAX_VALUE

any one of the Lists in this, or any element of a provided list is null