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
+5.1k Golang : Stop goroutine without channel
+10.6k Golang : Create S3 bucket with official aws-sdk-go package
+11.8k Golang : Print UTF-8 fonts on image example
+19.4k Golang : Accept input from user with fmt.Scanf skipped white spaces and how to fix it
+9.6k Golang : Convert octal value to string to deal with leading zero problem
+8.1k Golang : Add text to image and get OpenCV's X, Y co-ordinates example
+10.8k Golang : Fix fmt.Scanf() on Windows will scan input twice problem
+30.3k Golang : Interpolating or substituting variables in string examples
+27.8k Golang : Change a file last modified date and time
+15.1k Golang : How to convert(cast) IP address to string?
+26.7k Golang : Convert CSV data to JSON format and save to file
+14.7k Golang : How do I get the local IP (non-loopback) address ?