-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcombos.go
More file actions
43 lines (41 loc) · 936 Bytes
/
combos.go
File metadata and controls
43 lines (41 loc) · 936 Bytes
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
package combos
// New returns the combinations of n and k, explained
// in http://en.wikipedia.org/wiki/Combination, as a two dimensional
// slice of indexes. If n or k are negative or k > n the return value
// will be empty.
func New(n, k int) [][]int {
results := [][]int{}
if n <= 0 || k <= 0 || k > n {
return results
}
pool := indexRange(n)
indices := indexRange(k)
result := indexRange(k)
results = append(results, indexRange(k))
for {
i := k - 1
for ; i >= 0 && indices[i] == i+len(pool)-k; i-- {
}
if i < 0 {
break
}
indices[i]++
for j := i + 1; j < k; j++ {
indices[j] = indices[j-1] + 1
}
for ; i < len(indices); i++ {
result[i] = pool[indices[i]]
}
resultCopy := make([]int, len(result))
copy(resultCopy, result)
results = append(results, resultCopy)
}
return results
}
func indexRange(n int) []int {
r := []int{}
for i := 0; i < n; i++ {
r = append(r, i)
}
return r
}