shuffle array in Go

golang slice
golang probability
golang copy slice
get random from array golang
golang undefined rand
golang normal distribution
fisher–yates shuffle
golang random decimal

I tried to translate the following Python code to Go

import random

list = [i for i in range(1, 25)]

but found my Go version lengthy and awkward because there is no shuffle function and I had to implement interfaces and convert types.

What would be an idiomatic Go version of my code?

As your list is just the integers from 1 to 25, you can use Perm :

list := rand.Perm(25)
for i, _ := range list {

Note that using a permutation given by rand.Perm is an effective way to shuffle any array.

dest := make([]int, len(src))
perm := rand.Perm(len(src))
for i, v := range perm {
    dest[v] = src[i]

How to shuffle arrays and slices in Go, shuffle(array) # shuffles the array! Unfortunately it is a little trickier in Go, so in this post we are going to explore all of our options. We  In Ruby this is as simple as calling the shuffle method. array = [1, 2, 3, 4, 5] array.shuffle # shuffles the array! If you are transitioning into Go from a language like Python or Ruby, at some point or another you are going to start missing one of the many helper functions offered by the language.

dystroy's answer is perfectly reasonable, but it's also possible to shuffle without allocating any additional slices.

for i := range slice {
    j := rand.Intn(i + 1)
    slice[i], slice[j] = slice[j], slice[i]

See this Wikipedia article for more details on the algorithm. rand.Perm actually uses this algorithm internally as well.

Go: Shuffle slice or array, 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. CODE EXAMPLE How to create a random permutation of a slice or array in Go.

Go 1.10 might include an official Fisher-Yates shuffle function.

See CL 51891:

math/rand: add Shuffle

Shuffle uses the Fisher-Yates algorithm.

Since this is new API, it affords us the opportunity to use a much faster Int31n implementation that mostly avoids division.

As a result, BenchmarkPerm30ViaShuffle is about 30% faster than BenchmarkPerm30, despite requiring a separate initialization loop and using function calls to swap elements.

Documentation: pkg/math/rand/#Shuffle


words := strings.Fields("ink runs from the corners of my mouth")
rand.Shuffle(len(words), func(i, j int) {
    words[i], words[j] = words[j], words[i]

shuffle array in Go, As your list is just the integers from 1 to 25, you can use Perm : list := rand.Perm(​25) for i, _ := range list { list[i]++ }. Note that using a permutation  math/rand package of go provides a Shuffle method that can be used shuffle an array or a slice. This method pseudo-randomizes the order of elements using the default source. pseudo-randomizes means that for a fixed input seed it will generate the same randomization.

Answer by Evan Shaw has a minor bug. If we iterate through the slice from lowest index to highest, to get a uniformly (pseudo) random shuffle, according to the same article, we must choose a random integer from interval [i,n) as opposed to [0,n+1).

That implementation will do what you need for larger inputs, but for smaller slices, it will perform a non-uniform shuffle.

To utilize rand.Intn(), we can do:

    for i := len(slice) - 1; i > 0; i-- {
        j := rand.Intn(i + 1)
        slice[i], slice[j] = slice[j], slice[i]

following the same algorithm from Wikipedia article.

Shuffle an array, Shuffle an array. Question: How to shuffle an array using Go lang? Answer: Here is a go lang example that shows how shuffle an array using a random number  Since you’re passing ‘array’ as the single argument, a List is created insted, and it contains one item, which is the array. When you then use Collections.shuffle on this new list, it is shuffling a list with one item in it instead of shuffling the Integer objects in the array.

Maybe you can also use the following function:

func main() {
   slice := []int{10, 12, 14, 16, 18, 20}

func Shuffle(slice []int) {
   r := rand.New(rand.NewSource(time.Now().Unix()))
   for n := len(slice); n > 0; n-- {
      randIndex := r.Intn(n)
      slice[n-1], slice[randIndex] = slice[randIndex], slice[n-1]

Shuffle Array of Objects with Go Lang · GitHub, Shuffle Array of Objects with Go Lang. cards-shuffle.go. package hello. import (. "​net/http". "". "". Shuffle a set of numbers without duplicates. Example: // Init an array with set 1, 2, and 3. int[] nums = {1,2,3}; Solution solution = new Solution(nums); // Shuffle the array [1,2,3] and return its result.

Golang : How to shuffle elements in array or slice?, Seed function to randomize the elements position inside the array or slice. For example : package main import ( "fmt" "math/rand" "time" ) func  shuffle ( array ) : bool. This function shuffles (randomizes the order of the elements in) an array. It uses a pseudo random number generator that is not suitable for cryptographic purposes.

rand, func Shuffle(n int, swap func(i, j int)). Shuffle pseudo-randomizes the order of elements using the default  To shuffle an array of size n (indices in the range [0..n-1]): if n = 0 do nothing; if n > 0 (recursive step) shuffle the first n-1 elements of the array; choose a random index, x, in the range [0..n-1] swap the element at index n-1 with the element at index x

shuffle, package shuffle. import "". Package shuffle provides primitives for shuffling slices and user-defined collections. What I need to do is randomly shuffle an array of 25 numbers int[] arr = Enumerable.Range(0, 24).ToArray(); So that it still has all the numbers from 0 to 24 but in a random order.

  • This question has a shuffle() implementation: Treatment of Arrays in Go.
  • I'm unsure if the Perm method has changed since this answer, but it returns "a pseudo-random permutation of the integers [0,n)". In this scenario, the outcome would be a permutation of 0 to 24.
  • @JayJay that's why the numbers are incremented (another solution would have been to just change 0 to 25).
  • I take it this is the "inside-out" version in the article, and you elide the i!=j check?
  • Looking at the Wikipedia page, this seems to be the "modern algorithm" (first variant). The "inside-out" version seems to store the result in a new array, rather than doing the shuffle in place.
  • @Deleplace Thank you. I have included this link in the answer.