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?
As your list is just the integers from 1 to 25, you can use Perm :
Note that using a permutation given by
rand.Perm
is an effective way to shuffle any array.Use Shuffle() from the
math/rand
library.Here's an example:
Since it comes from the
math/rand
library it needs to be seeded. See here for more details.Raed's approach is very inflexible because of
[]interface{}
as input. Here is more convenient version for go>=1.8:Example usage:
And also, don't forget that a little copying is better than a little dependency
Maybe you can also use the following function:
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:following the same algorithm from Wikipedia article.
When using the
math/rand
package, do not forget to set a sourceSo I wrote a
Shuffle
function that takes this into consideration:And to use it:
If you would like to use it, you can find it here https://github.com/shomali11/util