How to shuffle the elements of a slice randomly in Golang?

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:

  1. The shuffle function takes a slice of integers as input.
  2. We seed the random number generator using rand.Seed with the current time in nanoseconds.
  3. We call 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.
  4. In the 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.