Skip to content

Commit

Permalink
docs: add high-level example to godocs
Browse files Browse the repository at this point in the history
  • Loading branch information
mroth committed Jun 19, 2020
1 parent d89c080 commit ea41bb4
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 16 deletions.
10 changes: 5 additions & 5 deletions weightedrand.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down
39 changes: 28 additions & 11 deletions weightedrand_test.go
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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.

Expand Down

0 comments on commit ea41bb4

Please sign in to comment.