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
+28k Golang : Connect to database (MySQL/MariaDB) server
+21k Golang : Convert(cast) string to rune and back to string example
+15.9k Golang : Generate universally unique identifier(UUID) example
+19.1k Golang : Populate dropdown with html/template example
+18.8k Golang : Padding data for encryption and un-padding data for decryption
+5.5k Unix/Linux : How to find out the hard disk size?
+12k Golang : Save webcamera frames to video file
+11k Golang : Proper way to test CIDR membership of an IP 4 or 6 address example
+11.6k Golang : convert(cast) float to string
+15k Golang : How to check if IP address is in range
+19.8k Golang : How to run your code only once with sync.Once object
+11.9k Golang : Perform sanity checks on filename example