-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcombination.go
More file actions
98 lines (89 loc) · 1.74 KB
/
combination.go
File metadata and controls
98 lines (89 loc) · 1.74 KB
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
package next
import "iter"
// Combination returns an iterator of combinations of n element from base without repetition
func Combination[T any](elements []T, r int) iter.Seq[[]T] {
if r < 0 {
r = 0
}
base := elements
n := len(elements)
if r > n {
return func(yield func([]T) bool) {}
}
results := 1
for i := 1; i <= r; i++ {
results = results * (n - r + i) / i
}
return func(yield func([]T) bool) {
idxs := make([]int, r)
for i := range idxs {
idxs[i] = i
}
if !yieldResult(yield, base, idxs) {
return
}
for i, j := 1, r-1; i < results; i++ {
if idxs[j] == j+n-r {
for idxs[j] == j+n-r {
j--
}
v := idxs[j] + 1
for i := j; i < r; i++ {
idxs[i] = v
v++
}
j = r - 1
} else {
idxs[j] = idxs[j] + 1
}
if !yieldResult(yield, base, idxs) {
return
}
}
}
}
// RepeatCombination returns a channel of combinantions of n element from base with repetition
func RepeatCombination[T any](elements []T, r int) iter.Seq[[]T] {
if r < 0 {
r = 0
}
base := elements
n := len(elements)
results := 1
for i := r + 1; i < n+r; i++ {
results *= i
}
for i := 1; i < n; i++ {
results /= i
}
return func(yield func([]T) bool) {
idxs := make([]int, r)
if !yieldResult(yield, base, idxs) {
return
}
for i, j := 1, r-1; i < results; i++ {
if idxs[j] == n-1 {
for idxs[j] == n-1 {
j--
}
v := idxs[j] + 1
for i := j; i < r; i++ {
idxs[i] = v
}
j = r - 1
} else {
idxs[j] = idxs[j] + 1
}
if !yieldResult(yield, base, idxs) {
return
}
}
}
}
func yieldResult[T any](yield func([]T) bool, base []T, index []int) bool {
res := make([]T, len(index))
for i, idx := range index {
res[i] = base[idx]
}
return yield(res)
}