From 7519463345537fad3299bfc1e4c777beeadcbcd1 Mon Sep 17 00:00:00 2001 From: gram Date: Fri, 17 Nov 2023 10:31:41 +0100 Subject: [PATCH] Fix Product2 for 0 and 1 inputs --- slices/slices.go | 19 +++++++++++-------- slices/slices_test.go | 2 ++ 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/slices/slices.go b/slices/slices.go index b101e0c..eedc3c6 100644 --- a/slices/slices.go +++ b/slices/slices.go @@ -63,6 +63,10 @@ func Intersect[S1 ~[]T, S2 ~[]T, T comparable](items1 S1, items2 S2) []T { // Product2 returns the cartesian product of elements in the given slices. func Product2[T any](items ...[]T) chan []T { c := make(chan []T, 1) + if len(items) == 0 { + close(c) + return c + } go product2(items, c, []T{}, 0) return c } @@ -77,14 +81,13 @@ func product2[T any](items [][]T, c chan []T, left []T, pos int) { result = append(result, el) c <- result } - return - } - - for _, el := range items[pos] { - result := make([]T, 0, len(left)+1) - result = append(result, left...) - result = append(result, el) - product2(items, c, result, pos+1) + } else { + for _, el := range items[pos] { + result := make([]T, 0, len(left)+1) + result = append(result, left...) + result = append(result, el) + product2(items, c, result, pos+1) + } } if pos == 0 { diff --git a/slices/slices_test.go b/slices/slices_test.go index ca1c341..12e316c 100644 --- a/slices/slices_test.go +++ b/slices/slices_test.go @@ -71,6 +71,8 @@ func TestProduct2(t *testing.T) { } f([][]int{{1, 2}, {3, 4}}, [][]int{{1, 3}, {1, 4}, {2, 3}, {2, 4}}) f([][]int{{1, 2}, {3}, {4, 5}}, [][]int{{1, 3, 4}, {1, 3, 5}, {2, 3, 4}, {2, 3, 5}}) + f([][]int{{1, 2}}, [][]int{{1}, {2}}) + f([][]int{}, [][]int{}) } func TestUnion(t *testing.T) {