This package provides a method to generate cartesian products (like python's itertools.product
) out of given slice.
go get github.com/kyo1/go-cartesian-product
All
function generates elements of all n-fold Cartesian product.
package main
import (
"context"
"fmt"
"github.com/kyo1/go-cartesian-product"
)
func main() {
chars := []interface{}{"a", "b", "c"}
// Generate a Cartesian product of all length
cnt := 0
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
for s := range cartesian.All(ctx, chars) {
fmt.Println(s)
cnt++
// Conditions for stopping the generator
if cnt == 10 {
cancel()
continue
}
}
// Output
// [a]
// [b]
// [c]
// [a b]
// [b b]
// [c b]
// [a c]
// [b c]
// [c c]
// [a a b]
}
Product
function generates elements of n-fold Cartesian product.
package main
import (
"context"
"fmt"
"github.com/kyo1/go-cartesian-product"
)
func main() {
chars := []interface{}{"a", "b", "c"}
// Generates n-fold Cartesian product
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
for s := range cartesian.Product(ctx, chars, 2) {
fmt.Println(s)
// The condition for terminating the generator is not required
// if condition {
// cancel()
// continue
// }
}
// Output
// [a a]
// [b a]
// [c a]
// [a b]
// [b b]
// [c b]
// [a c]
// [b c]
// [c c]
}