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.4k Golang : Gzip file example
+9.1k Golang : How to get ECDSA curve and parameters data?
+54.8k Golang : Unmarshal JSON from http response
+7.5k Golang : get the current working directory of a running program
+29.5k Golang : Get and Set User-Agent examples
+9.2k Golang : Qt Yes No and Quit message box example
+5.3k PHP : Convert CSV to JSON with YQL example
+36.1k Golang : Convert(cast) int64 to string
+7.1k Golang : Process json data with Jason package
+8.9k Golang : Create and shuffle deck of cards example
+12.9k Golang : How to get a user home directory path?