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
+9.9k Golang : Text file editor (accept input from screen and save to file)
+10.9k Golang : Intercept and process UNIX signals example
+7.4k Golang : Error reading timestamp with GORM or SQL driver
+16.9k Golang : How to tell if a file is compressed either gzip or zip ?
+13k Golang : Linear algebra and matrix calculation example
+6.7k Golang : constant 20013 overflows byte error message
+6.7k Golang : How to call function inside template with template.FuncMap
+16.5k Golang : Fix cannot convert buffer (type *bytes.Buffer) to type string error
+6.6k Nginx : Password protect a directory/folder
+10.8k Golang : Create S3 bucket with official aws-sdk-go package
+9.9k Golang : How to profile or log time spend on execution?
+23.3k Find and replace a character in a string in Go