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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With