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
+3.9k Detect if Google Analytics and Developer Media are loaded properly or not
+8k Android Studio : Rating bar example
+12.6k Swift : Convert (cast) Int or int32 value to CGFloat
+16.7k Golang : Set up source IP address before making HTTP request
+12.8k Python : Convert IPv6 address to decimal and back to IPv6
+6.1k Golang : How to get capacity of a slice or array?
+19.4k Golang : Close channel after ticker stopped example
+14.4k Golang : GUI with Qt and OpenCV to capture image from camera
+5.3k Golang : Get S3 or CloudFront object or file information
+9.5k Javascript : Read/parse JSON data from HTTP response
+7.7k Golang : Example of how to detect which type of script a word belongs to
+6.2k Golang : Selection sort example