-
Notifications
You must be signed in to change notification settings - Fork 1
/
phrase_array.go
81 lines (64 loc) · 1.68 KB
/
phrase_array.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
package libgochewing
import (
"errors"
"fmt"
)
type PhraseArray struct {
array []*PhraseArrayItem
}
type PhraseArrayItem struct {
phoneSeq []uint16
phrase []*Phrase
}
func newPhraseArray() (phraseArray *PhraseArray) {
phraseArray = new(PhraseArray)
phraseArray.array = make([]*PhraseArrayItem, 0, 1024)
return phraseArray
}
func newPhraseArrayItem(phoneSeq []uint16) (phraseArrayItem *PhraseArrayItem) {
phraseArrayItem = new(PhraseArrayItem)
phraseArrayItem.phoneSeq = phoneSeq
return phraseArrayItem
}
func (this *PhraseArray) insert(phrase *Phrase, phoneSeq []uint16) (err error) {
begin := 0
end := len(this.array)
for begin < end {
pos := (begin + end) / 2
compare := comparePhoneSeq(this.array[pos].phoneSeq, phoneSeq, 0)
if compare == 0 {
return this.array[pos].insert(phrase)
} else if compare > 0 {
begin = pos + 1
} else {
end = pos
}
}
this.array = append(this.array, nil)
copy(this.array[begin+1:], this.array[begin:])
newPhraseArrayItem := newPhraseArrayItem(phoneSeq)
newPhraseArrayItem.insert(phrase)
this.array[begin] = newPhraseArrayItem
return nil
}
func (this *PhraseArrayItem) insert(phrase *Phrase) (err error) {
pos := 0
for i, item := range this.phrase {
if isTheSamePhrase(item, phrase) {
return errors.New(fmt.Sprintf("Phrase %s already in phrase tree", phrase.phrase))
}
if phrase.frequency < item.frequency {
pos = i + 1
}
}
this.phrase = append(this.phrase, nil)
copy(this.phrase[pos+1:], this.phrase[pos:])
this.phrase[pos] = phrase
return nil
}
func (this *PhraseArrayItem) getLength() int {
return len(this.phoneSeq)
}
func (this *PhraseArrayItem) getPhoneAtPos(pos int) uint16 {
return this.phoneSeq[pos]
}