Golang : How to shuffle elements in array or slice?
Problem :
You have an array or slice with elements in natural order and you want to shuffle the elements.
Solution :
Use rand.Seed
function to randomize the elements position inside the array or slice.
For example :
package main
import (
"fmt"
"math/rand"
"time"
)
func shuffle(arr []int) {
t := time.Now()
rand.Seed(int64(t.Nanosecond())) // no shuffling without this line
for i := len(arr) - 1; i > 0; i-- {
j := rand.Intn(i)
arr[i], arr[j] = arr[j], arr[i]
}
}
func main() {
//list := rand.Perm(25)
list := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
fmt.Printf("Original : %v\n", list)
shuffledList := list
shuffle(shuffledList)
fmt.Printf("Shuffled : %v\n", shuffledList)
}
Output :
Original : [1 2 3 4 5 6 7 8 9 10]
Shuffled : [10 3 9 8 2 1 4 6 7 5]
See also : Golang : Generate random elements without repetition or duplicate
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+9.1k Golang : Qt Yes No and Quit message box example
+15.1k Golang : Intercept Ctrl-C interrupt or kill signal and determine the signal type
+4.4k MariaDB/MySQL : Form select statement or search query with Chinese characters
+7.3k Golang : Example of how to detect which type of script a word belongs to
+8.6k Golang : Go as a script or running go with shebang/hashbang style
+14.1k Golang : Overwrite previous output with count down timer
+4.4k Linux/MacOSX : How to symlink a file?
+22.1k Generate checksum for a file in Go
+22.3k Golang : Strings to lowercase and uppercase example
+21.7k Golang : How to run Golang application such as web server in the background or as daemon?
+7.8k Golang : Qt splash screen with delay example
+14.5k Golang : How to check for empty array string or string?