mirror of
https://github.com/jimeh/rands.git
synced 2026-02-19 03:16:39 +00:00
Add equivalent to `Shuffle` function from `math/rand` and `math/rand/v2` packages, but based on randomness from `crypto/rand` package. This allows cryptographically secure shuffling of data. Also add `ShuffleSlice` function that shuffles a slice of any type. BREAKING CHANGE: Minimum required Go version is now 1.18 due the `ShuffleSlice` using generics.
26 lines
443 B
Go
26 lines
443 B
Go
package randsmust_test
|
|
|
|
import (
|
|
"fmt"
|
|
|
|
"github.com/jimeh/rands/randsmust"
|
|
)
|
|
|
|
func ExampleShuffle() {
|
|
numbers := []int{1, 2, 3, 4, 5}
|
|
|
|
randsmust.Shuffle(len(numbers), func(i, j int) {
|
|
numbers[i], numbers[j] = numbers[j], numbers[i]
|
|
})
|
|
|
|
fmt.Println(numbers) // => [4 2 5 3 1]
|
|
}
|
|
|
|
func ExampleShuffleSlice() {
|
|
mixed := []any{1, "two", 3.14, true, nil}
|
|
|
|
randsmust.ShuffleSlice(mixed)
|
|
|
|
fmt.Println(mixed) // => [two <nil> true 3.14 1]
|
|
}
|