Created
May 24, 2019 13:14
-
-
Save earthboundkid/f4285d496fb45c07f46c44974de48d0d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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