Documentation ¶
Overview ¶
Package random provides a set of random selection utility functions
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Choice ¶
func Choice[T any](population []T) T
Choice returns a random element from the non-empty slice population
Choice will panic if the population is empty
Example ¶
// Fix the random order rand.Seed(1) words := strings.Fields("ink runs from the corners of my mouth") wordChoice := Choice(words) fmt.Println(wordChoice)
Output: runs
func ChoiceIndex ¶
ChoiceIndex returns the index to a random element from the non-empty slice population
ChoiceIndex will panic if the population is empty
Example ¶
// Fix the random order rand.Seed(1) words := strings.Fields("ink runs from the corners of my mouth") index := ChoiceIndex(words) fmt.Println(index)
Output: 1
func Sample ¶
Sample returns a sampleSize length slice of unique elements chosen from population. Used for random sampling without replacement.
Returns a new slice containing elements from the population while leaving the original population unchanged.
If the population contains repeats, then each occurrence is a possible selection in the sample.
Sample will panic if the sampleSize is greater than the length of the population or less than zero,
Example ¶
// Fix the random order rand.Seed(1) words := strings.Fields("ink runs from the corners of my mouth") wordSample := Sample(3, words) fmt.Println(wordSample)
Output: [of ink mouth]
func WeightedChoice ¶
func WeightedChoice[T any, W constraints.Integer](population []WeightedElement[T, W]) T
WeightedChoice returns a random element from the non-empty slice population based upon the relative weights in the population
Example ¶
// Fix the random order rand.Seed(1) var list []WeightedElement[string, uint] list = append(list, NewWeightedElement("first", uint(20))) list = append(list, NewWeightedElement("second", uint(30))) list = append(list, NewWeightedElement("third", uint(10))) fmt.Println(WeightedChoice(list))
Output: second
func WithProbability ¶
WithProbability returns true if the next random number is less than chance.
chance should be in the range 0.0 to 1.0
Example ¶
fmt.Println(WithProbability(1.0)) fmt.Println(WithProbability(0.0))
Output: true false
Types ¶
type WeightedElement ¶
type WeightedElement[T any, W constraints.Integer] struct { Element T Weight W }
WeightedElement associates an integer weight with an item to allow weighted selection
func NewWeightedElement ¶
func NewWeightedElement[T any, W constraints.Integer](element T, weight W) WeightedElement[T, W]
NewWeightedElement is a convenience function to create a WeightedElement structure