mirror of
https://github.com/jimeh/rands.git
synced 2026-02-19 11:26:38 +00:00
feat(shuffle)!: add Shuffle and ShuffleSlice functions (#11)
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.
This commit is contained in:
32
shuffle_example_test.go
Normal file
32
shuffle_example_test.go
Normal file
@@ -0,0 +1,32 @@
|
||||
package rands_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
"github.com/jimeh/rands"
|
||||
)
|
||||
|
||||
func ExampleShuffle() {
|
||||
numbers := []int{1, 2, 3, 4, 5}
|
||||
|
||||
err := rands.Shuffle(len(numbers), func(i, j int) {
|
||||
numbers[i], numbers[j] = numbers[j], numbers[i]
|
||||
})
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
fmt.Println(numbers) // => [2 4 5 1 3]
|
||||
}
|
||||
|
||||
func ExampleShuffleSlice() {
|
||||
mixed := []any{1, "two", 3.14, true, nil}
|
||||
|
||||
err := rands.ShuffleSlice(mixed)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
fmt.Println(mixed) // => [3.14 true 1 two <nil>]
|
||||
}
|
||||
Reference in New Issue
Block a user