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
+6.7k Golang : Skip or discard items of non-interest when iterating example
+5.7k Golang : Detect words using using consecutive letters in a given string
+19.2k Golang : When to use public and private identifier(variable) and how to make the identifier public or private?
+16.7k Golang : Merge video(OpenCV) and audio(PortAudio) into a mp4 file
+14.6k Golang : Overwrite previous output with count down timer
+14.1k Golang : Reverse IP address for reverse DNS lookup example
+19.3k Golang : Delete item from slice based on index/key position
+9.3k Golang : does not implement flag.Value (missing Set method)
+35.4k Golang : Strip slashes from string example
+10k Golang : Turn string or text file into slice example
+8.5k Golang : Ackermann function example
+9.9k Golang : Get current, epoch time and display by year, month and day