blob: 54079b89832da58268d1d32189139c3c3a4018ba [file] [log] [blame]
Tim Windelschmidt6d33a432025-02-04 14:34:25 +01001// Copyright The Monogon Project Authors.
2// SPDX-License-Identifier: Apache-2.0
3
Serge Bazanskide097942023-06-27 13:55:10 +02004package cartesian
5
6// Product returns cartesian product of arguments. Each argument must be a slice
7// of the same kind.
8func Product[T any](dimensions ...[]T) [][]T {
9 if len(dimensions) == 0 {
10 return nil
11 }
12
13 head, tail := dimensions[0], dimensions[1:]
14 tailProduct := Product[T](tail...)
15
16 var result [][]T
17 for _, v := range head {
18 if len(tailProduct) == 0 {
19 result = append(result, []T{v})
20 } else {
21 for _, ttail := range tailProduct {
22 element := []T{
23 v,
24 }
25 element = append(element, ttail...)
26 result = append(result, element)
27 }
28 }
29
30 }
31 return result
32}