Golang : Shuffle strings array
Okay, the previous tutorial on how to shuffle elements inside an array does not work with strings array. To shuffle array with strings, use this code example instead.
package main
import (
"fmt"
"math/rand"
"time"
)
func shuffle(src []string) []string {
final := make([]string, len(src))
rand.Seed(time.Now().UTC().UnixNano())
perm := rand.Perm(len(src))
for i, v := range perm {
final[v] = src[i]
}
return final
}
func main() {
str := []string{
"first",
"second",
"third",
}
shuffled := shuffle(str)
fmt.Printf("Original order : %v\n", str)
fmt.Printf("Shuffled order : %v\n", shuffled)
}
Sample output :
Original order : [first second third]
Shuffled order : [second third first]
See also : Golang : How to shuffle elements in array or slice?
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
+16.7k Golang : How to generate QR codes?
+20.1k Golang : Check if os.Stdin input data is piped or from terminal
+10.1k Golang : Detect number of faces or vehicles in a photo
+13.3k Golang : Read XML elements data with xml.CharData example
+29.3k Golang : How to create new XML file ?
+6.2k Golang : Detect face in uploaded photo like GPlus
+8.7k Golang : Take screen shot of browser with JQuery example
+5.7k Golang : List all packages and search for certain package
+5.8k Golang : Denco multiplexer example
+5.3k Golang : Intercept, inject and replay HTTP traffics from web server
+10.9k Golang : Fix go.exe is not compatible with the version of Windows you're running
+7.7k Golang : How to feed or take banana with Gorilla Web Toolkit Session package