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
+12.7k Golang : Listen and Serve on sub domain example
+19.8k Golang : Accept input from user with fmt.Scanf skipped white spaces and how to fix it
+23.8k Golang : Use regular expression to validate domain name
+5.9k Golang : Compound interest over time example
+14k Golang : Fix cannot use buffer (type bytes.Buffer) as type io.Writer(Write method has pointer receiver) error
+20.1k Golang : How to get own program name during runtime ?
+7k Golang : Squaring elements in array
+17.6k Golang : Upload/Receive file progress indicator
+11.1k Golang : How to determine a prime number?
+21.6k SSL : How to check if current certificate is sha1 or sha2
+6.2k Golang : How to get capacity of a slice or array?
+12k Golang : Sort and reverse sort a slice of runes