diff --git a/weightedrand.go b/weightedrand.go index cd8af62..6647f47 100644 --- a/weightedrand.go +++ b/weightedrand.go @@ -3,11 +3,11 @@ // each element to be selected not being equal, but defined by relative // "weights" (or probabilities). This is called weighted random selection. // -// There is an existing Go library that has a generic implementation of this as -// github.com/jmcvetta/randutil, which optimizes for the single operation case. -// In contrast, this package creates a presorted cache optimized for binary -// search, allowing repeated selections from the same set to be significantly -// faster, especially for large data sets. +// Compare this package with (github.com/jmcvetta/randutil).WeightedChoice, +// which is optimized for the single operation case. In contrast, this package +// creates a presorted cache optimized for binary search, allowing for repeated +// selections from the same set to be significantly faster, especially for large +// data sets. package weightedrand import ( diff --git a/weightedrand_test.go b/weightedrand_test.go index 8cadfa6..8ffa9d7 100644 --- a/weightedrand_test.go +++ b/weightedrand_test.go @@ -1,25 +1,31 @@ package weightedrand import ( + "fmt" "math/rand" "strconv" "testing" "time" ) -func init() { - rand.Seed(time.Now().UTC().UnixNano()) +// In this example, we create a Chooser to pick from amongst various emoji fruit +// runes. We assign a numeric weight to each choice. These weights are relative, +// not on any absolute scoring system. In this trivial case, we will assign a +// weight of 0 to all but one fruit, so that the output will be predictable. +func Example() { + chooser := NewChooser( + NewChoice('🍋', 0), + NewChoice('🍊', 0), + NewChoice('🍉', 0), + NewChoice('🥑', 42), + ) + fruit := chooser.Pick().(rune) + fmt.Printf("%c", fruit) + //Output: 🥑 } -func mockChoices(n int) []Choice { - choices := make([]Choice, 0, n) - for i := 0; i < n; i++ { - s := "⚽️" - w := rand.Intn(10) - c := NewChoice(s, uint(w)) - choices = append(choices, c) - } - return choices +func init() { + rand.Seed(time.Now().UTC().UnixNano()) } // TestWeightedChoice assembles a list of choices, weighted 0-9, and tests that @@ -96,6 +102,17 @@ func BenchmarkPick(b *testing.B) { } } +func mockChoices(n int) []Choice { + choices := make([]Choice, 0, n) + for i := 0; i < n; i++ { + s := "⚽️" + w := rand.Intn(10) + c := NewChoice(s, uint(w)) + choices = append(choices, c) + } + return choices +} + // This following is a historic artifact from comparative benchmarking with // randutil, however it is not critical to ongoing development.