-
Notifications
You must be signed in to change notification settings - Fork 36
/
helpers.go
66 lines (56 loc) · 1.11 KB
/
helpers.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
package gomarkov
import (
"sort"
"strings"
)
// Pair is a pair of consecutive states in a sequece
type Pair struct {
CurrentState NGram // n = order of the chain
NextState string // n = 1
}
// NGram is a array of words
type NGram []string
type sparseArray map[int]int
func (ngram NGram) key() string {
return strings.Join(ngram, "_")
}
func (s sparseArray) orderedKeys() []int {
keys := make([]int, 0, len(s))
for k := range s {
keys = append(keys, k)
}
sort.Ints(keys)
return keys
}
func (s sparseArray) sum() int {
sum := 0
for _, count := range s {
sum += count
}
return sum
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
func array(value string, count int) []string {
arr := make([]string, count)
for i := range arr {
arr[i] = value
}
return arr
}
// MakePairs generates n-gram pairs of consecutive states in a sequence
func MakePairs(tokens []string, order int) []Pair {
var pairs []Pair
for i := 0; i < len(tokens)-order; i++ {
pair := Pair{
CurrentState: tokens[i : i+order],
NextState: tokens[i+order],
}
pairs = append(pairs, pair)
}
return pairs
}