HiveBrain v1.2.0
Get Started
← Back to all entries
patterngoCritical

shuffle array in Go

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
shufflearraystackoverflow

Problem

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

Code Snippets

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

Context

Stack Overflow Q#12264789, score: 108

Revisions (0)

No revisions yet.