Documentation ยถ
Overview ยถ
Package weightedrand contains a performant data structure and algorithm used to randomly select an element from some kind of list, where the chances of each element to be selected not being equal, but defined by relative "weights" (or probabilities). This is called weighted random selection.
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.
Example ยถ
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.
chooser := NewChooser( NewChoice('๐', 0), NewChoice('๐', 0), NewChoice('๐', 0), NewChoice('๐ฅ', 42), ) fruit := chooser.Pick().(rune) fmt.Printf("%c", fruit)
Output: ๐ฅ
Index ยถ
Examples ยถ
Constants ยถ
This section is empty.
Variables ยถ
This section is empty.
Functions ยถ
This section is empty.
Types ยถ
type Choice ยถ
type Choice struct { Item interface{} Weight uint }
Choice is a generic wrapper that can be used to add weights for any item.
type Chooser ยถ
type Chooser struct {
// contains filtered or unexported fields
}
A Chooser caches many possible Choices in a structure designed to improve performance on repeated calls for weighted random selection.
func NewChooser ยถ
NewChooser initializes a new Chooser for picking from the provided Choices.