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.
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() 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[T any, W integer] struct { Item T Weight W }
Choice is a generic wrapper that can be used to add weights for any item.
type Chooser ¶
type Chooser[T any, W integer] 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.
func (Chooser[T, W]) Pick ¶
func (c Chooser[T, W]) Pick() T
Pick returns a single weighted random Choice.Item from the Chooser.
Utilizes global rand as the source of randomness. Safe for concurrent usage.
func (Chooser[T, W]) PickSource
deprecated
PickSource returns a single weighted random Choice.Item from the Chooser, utilizing the provided *rand.Rand source rs for randomness.
The primary use-case for this is avoid lock contention from the global random source if utilizing Chooser(s) from multiple goroutines in extremely high-throughput situations.
It is the responsibility of the caller to ensure the provided rand.Source is free from thread safety issues.
Deprecated: Since go1.21 global rand no longer suffers from lock contention when used in multiple high throughput goroutines, as long as you don't manually seed it. Use Chooser.Pick instead.