Add a general shuffler and deck shuffling.
This commit is contained in:
@ -2,6 +2,7 @@ package cardsim
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/rand"
|
||||
)
|
||||
|
||||
// InsertInto inserts one or more items into a slice at an arbitrary index.
|
||||
@ -98,3 +99,30 @@ func DeleteNFrom[T any](slice []T, loc, n int) []T {
|
||||
copy(slice[loc:], slice[loc+n:])
|
||||
return slice[:len(slice)-n]
|
||||
}
|
||||
|
||||
// ShuffleAll shuffles everything in slice, using the provided rand.Rand.
|
||||
// If no rand.Rand is provided, this uses the default source.
|
||||
func ShuffleAll[T any](slice []T, r *rand.Rand) {
|
||||
shuffle := rand.Shuffle
|
||||
if r != nil {
|
||||
shuffle = r.Shuffle
|
||||
}
|
||||
shuffle(len(slice), func(i, j int) {
|
||||
slice[i], slice[j] = slice[j], slice[i]
|
||||
})
|
||||
}
|
||||
|
||||
// ShufflePart shuffles the `n` elements of `slice` starting at `loc`
|
||||
// in-place, using the provided rand.Rand. If the range of items to
|
||||
// shuffle is not entirely within `slice`, this panics.
|
||||
//
|
||||
// If no rand.Rand is provided, this uses the default source.
|
||||
func ShufflePart[T any](slice []T, r *rand.Rand, loc, n int) {
|
||||
if loc < 0 || loc+n > len(slice) {
|
||||
panic(fmt.Sprintf("can't shuffle %d elements from a %d-element slice at location %d", n, len(slice), loc))
|
||||
}
|
||||
if n < 1 {
|
||||
return
|
||||
}
|
||||
ShuffleAll(slice[loc:loc+n], r)
|
||||
}
|
||||
|
Reference in New Issue
Block a user