Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
package main
import (
"fmt"
"strings"
)
func Combinations(n int, combs []int) (next func() bool) {
k := len(combs)
if k == 0 || n < k {
return func() bool { return false }
}
init := true
return func() bool {
if init {
for i := range combs {
combs[i] = i
}
init = false
return true
}
var (
i int
)
// Combination (n-k, n-k+1, ..., n) reached
// No more combinations can be generated
if combs[0] == n-k {
return false
}
for i = k - 1; i >= 0; i-- {
combs[i]++
if combs[i] < n-k+1+i {
break
}
}
// combs now looks like (..., x, n, n, n, ..., n).
// Turn it into (..., x, x + 1, x + 2, ...)
for i = i + 1; i < k; i++ {
combs[i] = combs[i-1] + 1
}
return true
}
}
func main() {
ss := strings.Split("a,b,c,d,e,f,g", ",")
combs := make([]int, 3)
for next := Combinations(len(ss), combs); next(); {
fmt.Println(ss[combs[0]], ss[combs[1]], ss[combs[2]])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.