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
546 Golang : Experimental Jawi programming language
+1.5k Golang : Scan forex opportunities by Bollinger bands
+3.5k Golang : Handle sub domain with Gin
+2.8k Golang : Get final or effective URL with Request.URL example
+3.5k Golang : Create and shuffle deck of cards example
+12.8k Golang : Set and Get HTTP request headers example
+10.5k Golang : Fix cannot download, $GOPATH not set error
+13.8k Google Chrome : Your connection to website is encrypted with obsolete cryptography
+55.5k Golang : How to return HTTP status code?
+5.7k Golang : Gorilla web tool kit secure cookie example
+3.4k Golang : Emulate NumPy way of creating matrix example
+3.4k Golang : Embedded or data bundling example