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
+10.3k Golang : Interfacing with PayPal's IPN(Instant Payment Notification) example
+9.2k Golang : Get all countries currencies code in JSON format
+5.6k Unix/Linux : How to test user agents blocked successfully ?
+9k Golang : Temperatures conversion example
+12.9k Golang : Convert(cast) int to int64
+11.9k Golang : md5 hash of a string
+7.6k Golang : Regular Expression find string example
+9.9k Golang : How to get quoted string into another string?
+4.5k Chrome : How to block socketloop.com links in Google SERP?
+14.8k JavaScript/JQuery : Detect or intercept enter key pressed example
+12.3k Golang : Arithmetic operation with numerical slices or arrays example
+6.9k Golang : Gorrila mux.Vars() function example