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
+4.7k Golang : Configure crontab to poll every two minutes 8am to 6pm Monday to Friday
+7.7k Golang : Accept any number of function arguments with three dots(...)
+5.1k Golang : Debug with Godebug
+4.1k Unix/Linux : secure copying between servers with SCP command examples
+17.1k Golang : How to get hour, minute, second from time?
+10.9k Golang : Flush and close file created by os.Create and bufio.NewWriter example
+17.8k Golang : Fix cannot download, $GOPATH not set error
+5.1k Golang : Selection sort example
+10.5k Golang : Verify Linux user password again before executing a program example
+6k Golang : How to detect if a sentence ends with a punctuation?
+13.5k Golang : Rename directory
+2k Golang : Fix go-cron set time not working issue