How to shuffle a slice in Go

Created
Modified

Using rand.Shuffle Function

Shuffle pseudo-randomizes the order of elements using the default Source.

package main

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

func main() {

  s := []string{"Japan", "Germany", "France"}

  rand.Seed(time.Now().UnixNano())
  // func Shuffle(n int, swap func(i, j int))
  rand.Shuffle(len(s), func(i, j int) { s[i], s[j] = s[j], s[i] })

  fmt.Printf("%q\n", s)
}
["Japan" "France" "Germany"]

Don't forget about the rand.Seed(), otherwise you got the same string every first time launch.

n is the number of elements. Shuffle panics if n < 0.

swap swaps the elements with indexes i and j.

Using rand.Intn Function

Use the rand.Seed and rand.Intn functions in package math/rand. Fisher–Yates algorithm:

package main

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

func main() {

  s := []string{"Japan", "Germany", "France"}

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

  fmt.Printf("%q\n", s)
}
["France" "Germany" "Japan"]

Intn returns, as an int, a non-negative pseudo-random number in [0,n)

It panics if n <= 0.

Related Tags