blob: fb42a2ba79ab38a3f1c7da244a3f163b419ed9c8 [file] [log] [blame]
Serge Bazanskide097942023-06-27 13:55:10 +02001package cartesian
2
3// Product returns cartesian product of arguments. Each argument must be a slice
4// of the same kind.
5func Product[T any](dimensions ...[]T) [][]T {
6 if len(dimensions) == 0 {
7 return nil
8 }
9
10 head, tail := dimensions[0], dimensions[1:]
11 tailProduct := Product[T](tail...)
12
13 var result [][]T
14 for _, v := range head {
15 if len(tailProduct) == 0 {
16 result = append(result, []T{v})
17 } else {
18 for _, ttail := range tailProduct {
19 element := []T{
20 v,
21 }
22 element = append(element, ttail...)
23 result = append(result, element)
24 }
25 }
26
27 }
28 return result
29}