-
Notifications
You must be signed in to change notification settings - Fork 0
/
wrand_test.go
131 lines (115 loc) · 2.15 KB
/
wrand_test.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
124
125
126
127
128
129
130
131
package wrand
import (
"fmt"
"github.com/stretchr/testify/assert"
"math"
"testing"
)
const maxRndPercentsError = 5
type testPickerPickCase struct {
Name string
Items *ItemsCollection
Picks int
}
func (t *testPickerPickCase) hasValue(value int) bool {
for _, i := range t.Items.GetAll() {
if i.Value == value {
return true
}
}
return false
}
func (t *testPickerPickCase) calcPercents() map[int]float64 {
//weight sum
weightSum := 0
for _, v := range t.Items.GetAll() {
weightSum += v.Weight
}
//percents
res := make(map[int]float64, t.Items.Count())
for _, v := range t.Items.GetAll() {
res[v.Value] = float64(v.Weight) / float64(weightSum) * 100
}
return res
}
func TestPicker_Pick(t *testing.T) {
var cases = []testPickerPickCase{
{
Name: "equal weight",
Items: NewItemsCollection(
[]Item{
{
Value: 1,
Weight: 50,
},
{
Value: 2,
Weight: 50,
},
{
Value: 3,
Weight: 50,
},
}),
Picks: 1000,
},
{
Name: "weights with a large spread",
Items: NewItemsCollection(
[]Item{
{
Value: 1,
Weight: 50,
},
{
Value: 2,
Weight: 100,
},
{
Value: 3,
Weight: 5000,
},
}),
Picks: 1000,
},
{
Name: "weights with a small spread",
Items: NewItemsCollection(
[]Item{
{
Value: 1,
Weight: 50,
},
{
Value: 2,
Weight: 55,
},
{
Value: 3,
Weight: 45,
},
}),
Picks: 1000,
},
}
for _, c := range cases {
t.Run(c.Name, func(t *testing.T) {
vPicks := map[int]int{}
vPercents := c.calcPercents()
for i := 0; i < c.Picks; i++ {
r := NewPicker().Pick(c.Items)
assert.True(t, c.hasValue(r.Value))
vPicks[r.Value]++
}
//calc random percents by value
for _, v := range c.Items.GetAll() {
vPercent := float64(vPicks[v.Value]) / float64(c.Picks) * 100
t.Log(fmt.Sprintf(
"Expected random percents: %.2f±%d; Actual: %.2f",
vPercents[v.Value], maxRndPercentsError, vPercent,
))
assert.True(t, math.Abs(vPercent-vPercents[v.Value]) <= maxRndPercentsError)
}
})
}
}