-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcombinations_with_replacement.go
54 lines (45 loc) · 1.48 KB
/
combinations_with_replacement.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
package iterium
import (
"math/big"
)
// CombinationsWithReplacementCount calculates the total number of combinations with replacement
// for a given set of n elements and a combination length of k.
func CombinationsWithReplacementCount(n, k int) int64 {
// The function uses the binomial coefficient formula to
// calculate the total number of combinations with replacement.
numerator := big.NewInt(1).Binomial(int64(n+k-1), int64(k))
return numerator.Int64()
}
// CombinationsWithReplacement generates all possible combinations with replacement
// of a given set of elements.
func CombinationsWithReplacement[T any](symbols []T, k int) Iter[[]T] {
arr := placeHolders(len(symbols))
total := CombinationsWithReplacementCount(len(symbols), k)
iter := Instance[[]T](total, false)
go func() {
defer IterRecover()
defer iter.Close()
comb := make([]int, k)
for i := range comb {
comb[i] = -1
}
// Define a recursive function to generate combinations.
var generateCombination func(start, combIndex int)
generateCombination = func(start, combIndex int) {
if combIndex == k {
// When a combination is complete, send it to the channel.
result := make([]T, k)
replacePlaceholders[T](symbols, comb, &result)
iter.Chan() <- result
return
}
for i := start; i < len(arr); i++ {
comb[combIndex] = arr[i]
// Recursively generate the rest of the combination.
generateCombination(i, combIndex+1)
}
}
generateCombination(0, 0)
}()
return iter
}