-
Notifications
You must be signed in to change notification settings - Fork 0
/
generate.go
35 lines (29 loc) · 915 Bytes
/
generate.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package slice
// Base of code
// https://play.golang.org/p/0bWDCibSUJ
// GenerateCombinations func
func GenerateCombinations(iter []string, length int) <-chan []string {
c := make(chan []string)
// Starting a separate goroutine that will create all the combinations,
// feeding them to the channel c
go func(c chan []string) {
defer close(c)
addIter(c, []string{}, iter, length)
}(c)
return c
}
// AddIter adds a letter to the combination to create a new combination.
// This new combination is passed on to the channel before we call AddIter once again
func addIter(c chan []string, combo []string, iter []string, length int) {
// Check if we reached the length limit
// If so, we just return without adding anything
if length <= 0 {
return
}
var newCombo []string
for _, ch := range iter {
newCombo = append(combo, string(ch))
c <- newCombo
addIter(c, newCombo, iter, length-1)
}
}