To shuffle the elements of a slice randomly in Golang, you can use the math/rand
package. Here's an example:
package main
import (
"fmt"
"math/rand"
"time"
)
func shuffle(slice []int) {
rand.Seed(time.Now().UnixNano())
rand.Shuffle(len(slice), func(i, j int) { slice[i], slice[j] = slice[j], slice[i] })
}
func main() {
slice := []int{1, 2, 3, 4, 5}
fmt.Println("Before shuffle:", slice)
shuffle(slice)
fmt.Println("After shuffle:", slice)
}
In this example:
shuffle
function takes a slice of integers as input.rand.Seed
with the current time in nanoseconds.rand.Shuffle
on the length of the slice, passing a custom swap function that swaps the elements at indices i
and j
in the slice.main
function, we create a slice of integers, print it before shuffling, shuffle it using the shuffle
function, and then print it again after shuffling.