-
Notifications
You must be signed in to change notification settings - Fork 0
/
weightedrandom_example_test.go
85 lines (67 loc) · 1.79 KB
/
weightedrandom_example_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
package weightedrandom_test
import (
"fmt"
"math/rand"
"github.com/minaguib/weightedrandom"
)
func Example_jarOfMarbles() {
marbles := []struct {
color string
weight uint
picked uint
}{
{"Red", 500, 0},
{"Blue", 250, 0},
{"Green", 125, 0},
{"Yellow", 120, 0},
{"Transparent", 4, 0},
{"Vantablack", 1, 0},
}
// Calculate slice of weights
weights := make([]float64, len(marbles))
for i, info := range marbles {
weights[i] = float64(info.weight)
}
// Initialize a new *WeightedRandom
wr, err := weightedrandom.New(weights)
if err != nil {
return
}
// For example/test purposes only, override internal randomizer with a deterministic one:
wr.Rand = rand.New(rand.NewSource(99))
// Pick 100,000 times and summarize
for i := 0; i < 100000; i++ {
idx := wr.Pick()
marbles[idx].picked++
//fmt.Printf("Picked: %v\n", marbles[idx].color)
}
// Output report
for _, info := range marbles {
fmt.Printf("Color %-11s weight=%3d picked=%5d times\n", info.color, info.weight, info.picked)
}
// Output:
// Color Red weight=500 picked=49999 times
// Color Blue weight=250 picked=24991 times
// Color Green weight=125 picked=12559 times
// Color Yellow weight=120 picked=11932 times
// Color Transparent weight= 4 picked= 415 times
// Color Vantablack weight= 1 picked= 104 times
}
func Example_fiftyFifty() {
weights := []float64{50, 50}
wr, err := weightedrandom.New(weights)
if err != nil {
return
}
// For example/test purposes only, override internal randomizer with a deterministic one:
wr.Rand = rand.New(rand.NewSource(99))
// Pick 100,000 times and summarize
picked := []uint{0, 0}
for i := 0; i < 100000; i++ {
idx := wr.Pick()
picked[idx]++
}
fmt.Printf("Picked: %v\n", picked)
// Output:
// Picked: [50070 49930]
}