Go: Shuffle slice or array

The rand.Shuffle function, which will be introduced in Go 1.10, shuffles an input sequence.

a := []int{1, 2, 3, 4, 5, 6, 7, 8}
rand.Seed(time.Now().UnixNano())
rand.Shuffle(len(a), func(i, j int) { a[i], a[j] = a[j], a[i] })
[5 8 6 4 3 7 2 1]

Without the call to rand.Seed, a program will produce the same sequence of pseudo-random numbers for each execution.

Before Go 1.10

Use the rand.Seed and rand.Intn functions in package math/rand:

a := []int{1, 2, 3, 4, 5, 6, 7, 8}
rand.Seed(time.Now().UnixNano())
for i := len(a) - 1; i > 0; i-- { // Fisher–Yates shuffle
        j := rand.Intn(i + 1)
        a[i], a[j] = a[j], a[i]
}

Comments

Be the first to comment!