flock-botnet/markov.go
markov.goRaw
1package main
2
3import (
4 "fmt"
5 "io/ioutil"
6 "strconv"
7 "strings"
8)
9
10type Markov struct{}
11
12/*type NextState struct {
13 Word string
14 Count int
15 Prob float64
16}*/
17type State struct {
18 Word string
19 Count int
20 Prob float64
21 NextStates []State
22}
23
24var markov Markov
25
26func addWordToStates(states []State, word string) ([]State, int) {
27 iState := -1
28 for i := 0; i < len(states); i++ {
29 if states[i].Word == word {
30 iState = i
31 }
32 }
33
34 if iState > 0 {
35 states[iState].Count++
36 } else {
37 var tempState State
38 tempState.Word = word
39 tempState.Count = 1
40
41 states = append(states, tempState)
42 iState = len(states) - 1
43 }
44 //fmt.Println(iState)
45 return states, iState
46}
47
48func countWordsProb(words []string) {
49 var states []State
50 totalWordsCount := 0
51 //count words
52 for i := 0; i < len(words); i++ {
53 var iState int
54 totalWordsCount++
55 states, iState = addWordToStates(states, words[i])
56 if iState != len(words)-1 {
57 states[iState].NextStates, _ = addWordToStates(states[iState].NextStates, words[iState+1])
58 }
59 }
60
61 //count prob
62 for i := 0; i < len(states); i++ {
63 states[i].Prob = (float64(states[i].Count) / float64(totalWordsCount) * 100)
64 for j := 0; j < len(states[i].NextStates); j++ {
65 states[i].NextStates[j].Prob = (float64(states[i].NextStates[j].Count) / float64(totalWordsCount) * 100)
66 }
67 }
68 fmt.Println("totalWordsCount: " + strconv.Itoa(totalWordsCount))
69 fmt.Println(states)
70}
71
72func textToWords(text string) []string {
73 s := strings.Split(text, " ")
74 words := s
75 return words
76}
77
78func readText(path string) (string, error) {
79 data, err := ioutil.ReadFile(path)
80 if err != nil {
81 //Do something
82 }
83 content := string(data)
84 return content, err
85}
86
87func (markov Markov) train(firstWord string, path string) string {
88 text, _ := readText(path)
89 words := textToWords(text)
90 countWordsProb(words)
91 return text
92}