Serge Bazanski | de09794 | 2023-06-27 13:55:10 +0200 | [diff] [blame] | 1 | package cartesian |
| 2 | |
| 3 | // Product returns cartesian product of arguments. Each argument must be a slice |
| 4 | // of the same kind. |
| 5 | func 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 | } |