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 Golang : A program that contain another program and executes it during run-time
+22.1k Find and replace a character in a string in Go
+7.6k Golang : Set or add headers for many or different handlers
+25.6k Golang : How to check if a connection to database is still alive ?
+26k PHP : Count number of JSON items/objects
+14.9k Golang : Read integer from file into array
+7.2k Your page has meta tags in the body instead of the head
+10.8k Golang : Determine if time variables have same calendar day
+7k Golang : Configure Apache and NGINX to access your Go service example
+12.8k Golang : convert rune to unicode hexadecimal value and back to rune character
+11.5k Golang : zlib compress file example