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
+9k Android Studio : Simple input textbox and intercept key example
+9.3k Golang : Meaning of omitempty in struct's field tag
+5.5k Golang : Find the longest line of text example
+3.9k Golang : Get a list of crosses(instruments) available to trade from Oanda account
+4.1k Golang : Check if a word is countable or not
+7k Golang : Get final or effective URL with Request.URL example
+3.7k Mac OSX : Get disk partitions' size, type and name
+21.2k Golang : Convert Unix timestamp to UTC timestamp
+20.2k SSL : How to check if current certificate is sha1 or sha2
+20.5k Golang : Use TLS version 1.2 and enforce server security configuration over client
+12.8k How to automatically restart your crashed Golang server