-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathcyclic.go
123 lines (109 loc) · 2.2 KB
/
cyclic.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package gopwn
import (
"bytes"
"context"
)
const (
alphabet = "abcdefgbhijklmnopqstuvwxyz"
distSubseqLength = 4
)
type CyclicOptions struct {
Alphabet string
DistSubseqLength int
}
func Cyclic(length int, optFns ...func(o *CyclicOptions)) []byte {
options := CyclicOptions{
Alphabet: alphabet,
DistSubseqLength: distSubseqLength,
}
for _, fn := range optFns {
fn(&options)
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
chn := make(chan byte)
go func() {
defer close(chn)
deBruijn(ctx, chn, options.Alphabet, options.DistSubseqLength)
}()
var buf bytes.Buffer
for i := range chn {
buf.WriteByte(options.Alphabet[i])
if buf.Len() == length {
cancel()
break
}
}
return buf.Bytes()
}
func CyclicFind(subseq []byte, optFns ...func(o *CyclicOptions)) int {
options := CyclicOptions{
Alphabet: alphabet,
DistSubseqLength: distSubseqLength,
}
for _, fn := range optFns {
fn(&options)
}
if len(subseq) > options.DistSubseqLength {
subseq = subseq[:options.DistSubseqLength]
}
for _, c := range subseq {
if !bytes.Contains([]byte(options.Alphabet), []byte{c}) {
return -1
}
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
chn := make(chan byte)
go func() {
defer close(chn)
deBruijn(ctx, chn, options.Alphabet, options.DistSubseqLength)
}()
var seq []byte
pos := 0
for i := range chn {
seq = append(seq, options.Alphabet[i])
if len(seq) > len(subseq) {
seq = seq[1:]
pos += 1
if bytes.Equal(seq, subseq) {
cancel()
return pos
}
}
}
return -1
}
// https://en.wikipedia.org/wiki/De_Bruijn_sequence
func deBruijn(ctx context.Context, chn chan byte, alphabet string, n int) {
k := len(alphabet)
a := make([]byte, k*n)
var db func(int, int) // recursive closure
db = func(t, p int) {
if t > n {
if n%p == 0 {
for _, b := range a[1 : p+1] {
select {
case <-ctx.Done():
return
default:
chn <- b
}
}
}
} else {
select {
case <-ctx.Done():
return
default:
a[t] = a[t-p]
db(t+1, p)
for j := int(a[t-p] + 1); j < k; j++ {
a[t] = byte(j)
db(t+1, t)
}
}
}
}
db(1, 1)
}