forked from pa-m/sklearn
/
itertools.go
93 lines (88 loc) · 1.54 KB
/
itertools.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
package preprocessing
func intrange(n int) []int {
r := make([]int, n)
for i := range r {
r[i] = i
}
return r
}
func yieldPoolIndices(ch chan<- []int, pool, indices []int) {
a := make([]int, len(indices))
for ii, i := range indices {
a[ii] = pool[i]
}
ch <- a
}
func combinations(pool []int, r int) chan []int {
n := len(pool)
ch := make(chan []int)
indices := intrange(r)
// yield tuple(pool[i] for i in indices)
go func() {
if r > n {
close(ch)
return
}
yieldPoolIndices(ch, pool, indices)
for {
var i int
loops := 0
//for i in reversed(range(r)):
for i = r - 1; i >= 0; i-- {
loops++
if indices[i] != i+n-r {
break
}
}
if i < 0 {
break
}
indices[i]++
for j := i + 1; j < r; j++ {
indices[j] = indices[j-1] + 1
}
yieldPoolIndices(ch, pool, indices)
}
close(ch)
}()
return ch
}
func combinationsWithReplacement(pool []int, r int) chan []int {
n := len(pool)
ch := make(chan []int)
indices := make([]int, r)
go func() {
if n == 0 && r > 0 {
close(ch)
return
}
yieldPoolIndices(ch, pool, indices)
for {
var i int
for i = r - 1; i >= 0; i-- {
if indices[i] != n-1 {
break
}
}
if i < 0 {
close(ch)
return
}
indi := indices[i] + 1
for ii := i; ii < r; ii++ {
indices[ii] = indi
}
yieldPoolIndices(ch, pool, indices)
}
}()
return ch
}
func bincount(a []int, minlength int) []int {
ret := make([]int, minlength)
for _, ai := range a {
if ai >= 0 && ai < minlength {
ret[ai]++
}
}
return ret
}