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
+8.2k Golang : How to unmarshal JSON inner/nested value and assign to specific struct?
+4.1k CloudFlare : Another way to get visitor's real IP address
+7k Golang : Web(Javascript) to server-side websocket example
+4k Golang : Compound interest over time example
+9.2k CodeIgniter : How to check if a session exist in PHP?
+11k Swift : Convert (cast) Int to String ?
+4.9k Golang : Check from web if Go application is running or not
+10.7k Golang : Rename directory
+17.6k Golang : Convert long hexadecimal with strconv.ParseUint example
+4.6k Golang : Calculate how many weeks left to go in a given year