shuffle an array in go

To shuffle an array in Go, we can use the math/rand package. Here is an example code snippet that shuffles an array of integers:

main.go
package main

import (
    "fmt"
    "math/rand"
    "time"
)

func shuffle(arr []int) {
    rand.Seed(time.Now().UnixNano())
    for i := len(arr) - 1; i >= 1; i-- {
        j := rand.Intn(i + 1)
        arr[i], arr[j] = arr[j], arr[i]
    }
}

func main() {
    arr := []int{1, 2, 3, 4, 5}
    fmt.Println("Before shuffle:", arr)
    shuffle(arr)
    fmt.Println("After shuffle:", arr)
}
390 chars
23 lines

In the shuffle function, we seed the random generator with the current Unix time in nanoseconds, ensuring that different runs of the program produce different shufflings. Then we loop from the end of the array to the beginning, randomly selecting one of the remaining indices and swapping their positions with the current index. Finally, in the main function, we initialize the array and print it before and after shuffling it.

gistlibby LogSnag