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
+5.5k Golang : Error handling methods
+17.3k Golang : Upload/Receive file progress indicator
+6.4k Golang : Check if password length meet the requirement
+11.8k Golang : Perform sanity checks on filename example
+8.2k PHP : How to parse ElasticSearch JSON ?
+11.5k Golang : Setup API server or gateway with Caddy and http.ListenAndServe() function example
+5.2k Golang : fmt.Println prints out empty data from struct
+9.4k Golang : Eroding and dilating image with OpenCV example
+14.1k Golang : How to check if your program is running in a terminal
+8.5k Golang : Random integer with rand.Seed() within a given range
+17.8k Golang : Check if a directory exist or not
+13.2k Golang : Qt progress dialog example