| Tim Windelschmidt | 6d33a43 | 2025-02-04 14:34:25 +0100 | [diff] [blame] | 1 | // Copyright The Monogon Project Authors. |
| 2 | // SPDX-License-Identifier: Apache-2.0 |
| 3 | |
| Serge Bazanski | de09794 | 2023-06-27 13:55:10 +0200 | [diff] [blame] | 4 | package cartesian |
| 5 | |
| 6 | // Product returns cartesian product of arguments. Each argument must be a slice |
| 7 | // of the same kind. |
| 8 | func 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 | } |