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
+10.1k Golang : Bcrypting password
+13.1k Golang : Convert(cast) int to int64
+25.4k Golang : convert rune to integer value
+6.2k Golang : Extract sub-strings
+8.1k Golang : Add build version and other information in executables
+7.3k Golang : Accessing dataframe-go element by row, column and name example
+7.1k Golang : Null and nil value
+9.1k Golang : Simple histogram example
+5.2k Python : Convert(cast) string to bytes example
+4.9k Google : Block or disable caching of your website content
+17.1k Golang : Find file size(disk usage) with filepath.Walk
+7.7k Golang : Scan files for certain pattern and rename part of the files