forked from dolthub/go-mysql-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
quick_perm.go
52 lines (48 loc) · 883 Bytes
/
quick_perm.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
package analyzer
import "io"
// quickPerm is an in-place permutation algorithm.
// The original array passed into quickPerm
// is mutated by every .Next() call.
// Use copy(newArray, perm) to save an intermediate
// result.
type quickPerm struct {
a []int
n int
p []int
i int
init bool
}
func newQuickPerm(a []int) *quickPerm {
return &quickPerm{
a: a,
n: len(a),
p: make([]int, len(a)),
i: 1,
}
}
// Next returns the next array permutation
// refer to https://www.quickperm.org for pseudocode
func (p *quickPerm) Next() ([]int, error) {
if !p.init {
p.init = true
return p.a, nil
}
for p.i < p.n {
if p.p[p.i] < p.i {
var j int
if p.i%2 == 1 {
j = p.p[p.i]
} else {
j = 0
}
p.a[p.i], p.a[j] = p.a[j], p.a[p.i]
p.p[p.i]++
p.i = 1
return p.a, nil
} else {
p.p[p.i] = 0
p.i++
}
}
return nil, io.EOF
}