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
+15.2k Golang : Save(pipe) HTTP response into a file
+8k Golang : Handle Palindrome string with case sensitivity and unicode
+19.9k Golang : Count JSON objects and convert to slice/array
+10.2k Golang : How to get quoted string into another string?
+13.6k Golang : Query string with space symbol %20 in between
+20.3k Golang : Determine if directory is empty with os.File.Readdir() function
+5.4k How to check with curl if my website or the asset is gzipped ?
+8.6k Android Studio : Import third-party library or package into Gradle Scripts
+14.2k Golang : syscall.Socket example
+5.9k Golang : Shuffle array of list
+19.6k Golang : Close channel after ticker stopped example
+11.6k Golang : Display a text file line by line with line number example