To shuffle an array in Go, we can use the math/rand
package. Here is an example code snippet that shuffles an array of integers:
main.go390 chars23 lines
In the shuffle
function, we seed the random generator with the current Unix time in nanoseconds, ensuring that different runs of the program produce different shufflings. Then we loop from the end of the array to the beginning, randomly selecting one of the remaining indices and swapping their positions with the current index. Finally, in the main
function, we initialize the array and print it before and after shuffling it.
gistlibby LogSnag