Golang : Shuffle array of list
Continue from previous tutorial on how to shuffle an array of strings, to shuffle array of list is not really straight forward, but it can be done easily with rand.Perm()
function. Use this code example to shuffle an array of list.
package main
import (
"fmt"
"math/rand"
"time"
)
func shuffleList(start, end int) []int {
if end < start {
start, end = end, start
}
length := end - start
rand.Seed(time.Now().UTC().UnixNano())
list := rand.Perm(length)
for index, _ := range list {
list[index] += start
}
return list
}
func main() {
mapList := make([]map[int]int, 3)
mapList[0] = map[int]int{1: 1}
mapList[1] = map[int]int{2: 2}
mapList[2] = map[int]int{3: 3}
shuffled := shuffleList(0, len(mapList))
fmt.Printf("Original order : %v\n", mapList)
fmt.Printf("Shuffled order : %v\n", shuffled)
}
Sample output :
Original order : [map[1:1] map[2:2] map[3:3]]
Shuffled order : [1 0 2]
See also : Golang : Shuffle strings array
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
+7.8k Setting $GOPATH environment variable for Unix/Linux and Windows
+34.9k Golang : Upload and download file to/from AWS S3
+5.8k AWS S3 : Prevent Hotlinking policy
+6.4k Golang : Totalize or add-up an array or slice example
+19.7k Golang : Accept input from user with fmt.Scanf skipped white spaces and how to fix it
+23.6k Golang : Fix type interface{} has no field or no methods and type assertions example
+9.5k Golang : Quadratic example
+29.7k Golang : How to declare kilobyte, megabyte, gigabyte, terabyte and so on?
+20.6k Golang : Convert date string to variants of time.Time type examples
+22k Golang : Match strings by wildcard patterns with filepath.Match() function
+9.7k Golang : Turn string or text file into slice example
+8.5k Python : Fix SyntaxError: Non-ASCII character in file, but no encoding declared