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
+6.4k Golang : How to detect if a sentence ends with a punctuation?
+8k Golang : Heap sort example
+20.1k Golang : For loop continue,break and range
+7.1k Golang : Get all countries phone codes
+6.5k Golang : Word limiter example
+26.9k Golang : Decode/unmarshal unknown JSON data type with map[string]interface
+8.4k Golang : Scramble and unscramble text message by randomly replacing words
+9k PHP : Get coordinates latitude/longitude from string
+28.5k Golang : Get time.Duration in year, month, week or day
+15k Golang : Generate universally unique identifier(UUID) example
+13.7k Golang : Rename directory