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
+6.1k Golang : Measure execution time for a function
+6k Golang : Compound interest over time example
+19.2k Golang : Delete item from slice based on index/key position
+19.8k Golang : Archive directory with tar and gzip
+7.9k Golang : Gomobile init produce "iphoneos" cannot be located error
+14.2k Golang : syscall.Socket example
+8.3k Golang : Find relative luminance or color brightness
+81.1k Golang : How to return HTTP status code?
+20.2k Golang : Count number of digits from given integer value
+5.7k Fix yum-complete-transaction error
+17.6k Golang : Find smallest number in array
+25.3k Golang : Storing cookies in http.CookieJar example