This repository has been archived by the owner on Aug 3, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
util_random_test.go
116 lines (112 loc) · 2.25 KB
/
util_random_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
package gago
import (
"errors"
"fmt"
"math"
"math/rand"
"testing"
"time"
)
func TestRandomInts(t *testing.T) {
var (
src = rand.NewSource(time.Now().UnixNano())
rng = rand.New(src)
testCases = []struct {
k, min, max int
}{
{1, 0, 1},
{1, 0, 2},
{2, 0, 2},
}
)
for i, tc := range testCases {
t.Run(fmt.Sprintf("TC %d", i), func(t *testing.T) {
var ints = randomInts(tc.k, tc.min, tc.max, rng)
// Check the number of generated integers
if len(ints) != tc.k {
t.Error("randomInts didn't generate the right number of integers")
}
// Check the bounds of each generated integer
for _, integer := range ints {
if integer < tc.min || integer >= tc.max {
t.Error("randomInts didn't generate integers in the desired range")
}
}
// Check the generated integers are unique
for i, a := range ints {
for j, b := range ints {
if i != j && a == b {
t.Error("randomInts didn't generate unique integers")
}
}
}
})
}
}
func TestSampleInts(t *testing.T) {
var testCases = []struct {
ints []int
k int
err error
}{
{
ints: []int{1, 2, 3},
k: 0,
err: nil,
},
{
ints: []int{1, 2, 3},
k: 1,
err: nil,
},
{
ints: []int{1, 2, 3},
k: 2,
err: nil,
},
{
ints: []int{1, 2, 3},
k: 3,
err: nil,
},
{
ints: []int{1, 2, 3},
k: 4,
err: errors.New("k > len(ints)"),
},
}
var rng = newRand()
for i, tc := range testCases {
t.Run(fmt.Sprintf("TC %d", i), func(t *testing.T) {
var ints, idxs, err = sampleInts(tc.ints, tc.k, rng)
if (err == nil) != (tc.err == nil) {
t.Error("Error")
} else {
if err == nil && (len(ints) != tc.k || len(idxs) != tc.k) {
t.Error("Error")
}
}
})
}
}
func TestRandomWeights(t *testing.T) {
var (
sizes = []int{1, 30, 500}
limit = math.Pow(1, -10)
)
for _, size := range sizes {
var weights = randomWeights(size)
// Test the length of the resulting slice
if len(weights) != size {
t.Error("Size problem with randomWeights")
}
// Test the elements in the slice sum up to 1
var sum float64
for _, weight := range weights {
sum += weight
}
if math.Abs(sum-1.0) > limit {
t.Error("Sum problem with randomWeights")
}
}
}