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
+9.4k Golang : How to find out similarity between two strings with Jaro-Winkler Distance?
+6k Cash Flow : 50 days to pay your credit card debt
+14.4k Golang : Convert IP version 6 address to integer or decimal number
+11.8k Golang : Simple file scaning and remove virus example
+20.4k Golang : Compare floating-point numbers
+17.4k Google Chrome : Your connection to website is encrypted with obsolete cryptography
+21.1k PHP : Convert(cast) int to double/float
+7.7k Golang : Detect sample rate, channels or latency with PortAudio
+7.5k Golang : Calculate how many weeks left to go in a given year
+5.6k Golang : What is StructTag and how to get StructTag's value?
+13.8k Golang : Strings comparison