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
+8.6k Golang : Eroding and dilating image with OpenCV example
+32.8k Golang : How to stream file to client(browser) or write to http.ResponseWriter?
+10.1k CodeIgniter : How to check if a session exist in PHP?
+11.9k Golang : List objects in AWS S3 bucket
+13.5k Golang : Find commonalities in two slices or arrays example
+3.6k Adding Skype actions such as call and chat into web page examples
+16.1k Golang : When to use init() function?
+17.1k Golang : Implement getters and setters
+19.6k Golang : Create and resolve(read) symbolic links
+8.1k Golang : Timeout example
+12.6k Golang : How to check if a file is hidden?
+15.1k Golang :Trim white spaces from a string