shuffle the elements in an array in Go
Code snippet on how to shuffle the elements in an array in Go
func Shuffle(slice []int) []int {
r := rand.New(rand.NewSource(time.Now().Unix()))
for len(slice) > 0 {
n := len(slice)
randIndex := r.Intn(n)
slice[n-1], slice[randIndex] = slice[randIndex], slice[n-1]
slice = slice[:n-1]
}
return slice
}
This is a function named “Shuffle” which takes an array of integers as the parameter. We create a random number generator which will be used to generate a random index later. Then, we have a while loop where the condition is that the slice size is greater than 0. Inside the loop, we assign the length of the slice to n, generate a random index position in the range of index positions of the slice and assign it to randIndex. Then, we swap the elements at the last index position with the element at the random index position. Finally, we update the slice to exclude the last element from the existing slice. This loop will continue until the length of the slice is 0 and the slice will be fully shuffled. We return the shuffled slices after the loop is complete.