Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shuffle array in Go

Tags:

arrays

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?

like image 238
deamon Avatar asked Sep 04 '12 13:09

deamon


People also ask

How to shuffle an array in golang?

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.

Can you shuffle an array in Python?

Shuffle an Array in Python Using the random.shuffle() method takes a sequence as input and shuffles it. The important thing to note here is that the random. shuffle() does not return a new sequence as output but instead shuffles the original sequence.

What is random shuffle in Python?

Python Random shuffle() Method The shuffle() method takes a sequence, like a list, and reorganize the order of the items. Note: This method changes the original list, it does not return a new list.


1 Answers

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.

like image 163
Evan Shaw Avatar answered Sep 24 '22 23:09

Evan Shaw