-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
92 lines (74 loc) · 1.92 KB
/
main.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
package main
import (
"fmt"
"math/rand"
"time"
)
const (
totalNodes = 10
quorumSize = 14
sampleSize = 20
decisionThreshold = 20
)
func init() {
rand.Seed(time.Now().UnixNano())
}
func main() {
preferences := []string{"orange", "blue", "green"}
// Generate nodes with preference
nodes := generateNodesWithPref(preferences)
// Every node queries 10 other nodes
start := time.Now()
for ni := 0; ni < totalNodes; ni++ {
success := 0
totalRound := 0
startTime := time.Now()
for ri := 0; success < decisionThreshold; ri++ {
totalRound++
chosenPrefs := make(map[string]int, sampleSize)
for i := 0; i <= sampleSize; i++ {
diffNodePref := nodes[rand.Intn(totalNodes)]
_, exists := chosenPrefs[diffNodePref]
if !exists {
chosenPrefs[diffNodePref] = 1
} else {
chosenPrefs[diffNodePref]++
}
}
mostChosenPref, highestChosen := getMostChosenPref(nodes[ni], preferences, chosenPrefs)
if highestChosen >= quorumSize {
if mostChosenPref == nodes[ni] {
success++
} else {
nodes[ni] = mostChosenPref
success = 1
}
} else {
success = 0
}
}
since := time.Since(startTime)
fmt.Printf("\n node: %v, round: %v, chosen: %v, dur: %s, succ: %v\n", ni, totalRound, nodes[ni], since, success)
// fmt.Println("OWN NEW: ", node)
}
since := time.Since(start)
fmt.Printf("\n%s\n", since)
}
func generateNodesWithPref(preferences []string) []string {
nodes := make([]string, totalNodes)
for i := 0; i < totalNodes; i++ {
nodes[i] = preferences[rand.Intn(len(preferences))]
}
return nodes
}
func getMostChosenPref(initialPref string, preferences []string, chosenPrefs map[string]int) (string, int) {
newPref := initialPref
highestChosen := 0
for _, preference := range preferences {
if chosenPrefs[preference] > highestChosen {
highestChosen = chosenPrefs[preference]
newPref = preference
}
}
return newPref, highestChosen
}