-
Notifications
You must be signed in to change notification settings - Fork 4
/
combination.go
66 lines (57 loc) · 1.27 KB
/
combination.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
// https://www4.uwsp.edu/math/nwodarz/Math209Files/209-0809F-L10-Section06_03-AlgorithmsForGeneratingPermutationsAndCombinations-Notes.pdf
package main
import (
"fmt"
)
func main() {
// An RLC circuit can have the following combinations:
// [RL, RC, LC, RLC], we can generate the combinations
// by having a blank as another element inside of the nCr framework
// as it represents a state we can pick
// outputs depend on the order of the array, but they are the same
// if we sort them at the end
combination(4, 3, mkstrprint([]string{"R", "L", " ", "C"}))
combination(4, 3, mkstrprint([]string{"L", "R", "C", " "}))
}
func mkstrprint(p []string) func(int, int, []int) {
return func(n, r int, c []int) {
for i := 1; i <= r; i++ {
fmt.Printf("%s ", p[c[i]-1])
}
fmt.Println()
}
}
func combination(n, r int, f func(int, int, []int)) {
s := make([]int, r+1)
for i := 1; i <= r; i++ {
s[i] = i
}
f(n, r, s)
k := ncr(n, r)
for i := 2; i <= k; i++ {
m := r
M := n
for s[m] == M {
m--
M--
}
s[m]++
for j := m + 1; j <= r; j++ {
s[j] = s[j-1] + 1
}
f(n, r, s)
}
}
func ncr(n, r int) int {
return fact(n) / (fact(r) * fact(n-r))
}
func fact(n int) int {
if n <= 1 {
return 1
}
r := 1
for i := 2; i <= n; i++ {
r *= i
}
return r
}