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
+18.8k Golang : Count number of digits from given integer value
+17.8k Golang : How to get own program name during runtime ?
+7.5k Golang : Executing and evaluating nested loop in html template
+23.3k Golang : Create PDF file from HTML file
+15.6k Golang : How to tell if a file is compressed either gzip or zip ?
+4.3k PHP : Fix Call to undefined function curl_init() error
+12.4k Golang : Human readable time elapsed format such as 5 days ago
+10.2k Golang : Display a text file line by line with line number example
+4.5k Golang : ROT32768 (rotate by 0x80) UTF-8 strings example
+8.7k Golang : Check if user agent is a robot or crawler example
+4.7k Golang : Configure crontab to poll every two minutes 8am to 6pm Monday to Friday
+14.9k Golang : Get file permission