Skip to content

Commit

Permalink
Merge pull request #32 from life4/fix-product2
Browse files Browse the repository at this point in the history
Fix Product2 for 0 and 1 inputs
  • Loading branch information
orsinium authored Nov 17, 2023
2 parents 6bf6cd6 + 7519463 commit 83c9345
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 8 deletions.
19 changes: 11 additions & 8 deletions slices/slices.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand All @@ -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 {
Expand Down
2 changes: 2 additions & 0 deletions slices/slices_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down

0 comments on commit 83c9345

Please sign in to comment.