go4kids/random.go

58 lines
1.8 KiB
Go

package go4kids
import (
"math/rand"
"time"
)
// RandomInt is a function that returns a random integer between min and max. To
// generate a large number of random integers, use RandomSequence instead.
func RandomInt(min, max int) int {
rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
return min + rnd.Intn(max-min+1)
}
// RandomChoice is a function that returns a random element from a slice.
func RandomChoice[T any](s []T) T {
rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
return s[rnd.Intn(len(s))]
}
// Shuffle is a function that shuffles a slice in-place using the Fisher-Yates algorithm.
func Shuffle[T any](slice []T) {
// Seed the random number generator with the current time in nanoseconds.
rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
// Loop over the slice of strings, starting from the end and working backwards.
for i := len(slice) - 1; i > 0; i-- {
// Generate a random number between 0 and i.
j := rnd.Intn(i + 1)
// Swap the value at index i with the value at index j.
slice[i], slice[j] = slice[j], slice[i]
}
}
// RandomRange is a function that returns a slice of random integers between min and max.
func RandomRange(min, max, length int) []int {
rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
s := make([]int, length)
for i := range s {
s[i] = min + rnd.Intn(max-min+1)
}
return s
}
// RandomSequence is a function that returns a channel of random integers between min and max.
// This method is more efficient than RandomRange, and can be used to generate
// an arbitrarily large number of random integers.
func RandomSequence(min, max, length int) chan int {
c := make(chan int)
go func() {
rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
for i := 0; i < length; i++ {
c <- min + rnd.Intn(max-min+1)
}
close(c)
}()
return c
}