-
Notifications
You must be signed in to change notification settings - Fork 4
/
combinations.go
120 lines (94 loc) · 2.26 KB
/
combinations.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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package itertools
//List is a list of elements of any kind/type
type List []interface{}
//GenCombinations generates, from two natural numbers n > r,
//all the possible combinations of r indexes taken from 0 to n-1.
//For example if n=3 and r=2, the result will be:
//[0,1], [0,2] and [1,2]
func GenCombinations(n, r int) <-chan []int {
if r > n {
panic("Invalid arguments")
}
ch := make(chan []int)
go func() {
result := make([]int, r)
for i := range result {
result[i] = i
}
temp := make([]int, r)
copy(temp, result) // avoid overwriting of result
ch <- temp
for {
for i := r - 1; i >= 0; i-- {
if result[i] < i+n-r {
result[i]++
for j := 1; j < r-i; j++ {
result[i+j] = result[i] + j
}
temp := make([]int, r)
copy(temp, result) // avoid overwriting of result
ch <- temp
break
}
}
if result[0] >= n-r {
break
}
}
close(ch)
}()
return ch
}
//CombinationsInt generates all the combinations of r elements
//extracted from an slice of integers
func CombinationsInt(iterable []int, r int) chan []int {
ch := make(chan []int)
go func() {
length := len(iterable)
for comb := range GenCombinations(length, r) {
result := make([]int, r)
for i, val := range comb {
result[i] = iterable[val]
}
ch <- result
}
close(ch)
}()
return ch
}
//CombinationsStr generates all the combinations of r elements
//extracted from an slice of strings
func CombinationsStr(iterable []string, r int) chan []string {
ch := make(chan []string)
go func() {
length := len(iterable)
for comb := range GenCombinations(length, r) {
result := make([]string, r)
for i, val := range comb {
result[i] = iterable[val]
}
ch <- result
}
close(ch)
}()
return ch
}
//CombinationsList generates all the combinations of r elements
//extracted from a List (an arbitrary list of elements).
//A List can be created for instance, as follows
//myList := List{"a", "b", 13, 3.523}
func CombinationsList(iterable List, r int) chan List {
ch := make(chan List)
go func() {
length := len(iterable)
for comb := range GenCombinations(length, r) {
result := make(List, r)
for i, val := range comb {
result[i] = iterable[val]
}
ch <- result
}
close(ch)
}()
return ch
}