arraysgo

shuffle array in Go


I tried to translate the following Python code to Go

import random

list = [i for i in range(1, 25)]
random.shuffle(list)
print(list)

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?


Solution

  • 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 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]
    }