Golang math/rand.Seed() function example
package math/rand
Golang math/rand.Seed() function usage example
package main
import (
"fmt"
"math/rand"
"time"
)
func shuffle(arr []int) {
t := time.Now()
rand.Seed(int64(t.Nanosecond())) // no shuffling without Seed
for i := len(arr) - 1; i > 0; i-- {
j := rand.Intn(i)
arr[i], arr[j] = arr[j], arr[i]
}
}
func main() {
//list := rand.Perm(25)
list := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
fmt.Printf("Original : %v\n", list)
shuffledList := list
shuffle(shuffledList)
fmt.Printf("Shuffled : %v\n", shuffledList)
}
References :
http://golang.org/pkg/math/rand/#Seed
https://www.socketloop.com/tutorials/golang-how-to-shuffle-elements-in-array-or-slice
Advertisement
Something interesting
Tutorials
+46.2k Golang : Read tab delimited file with encoding/csv package
+14.3k Golang : Get uploaded file name or access uploaded files
+17.7k Golang : [json: cannot unmarshal object into Go value of type]
+6.8k Swift : substringWithRange() function example
+14.8k Golang : Find commonalities in two slices or arrays example
+9.2k Golang : Write multiple lines or divide string into multiple lines
+12.6k Golang : Drop cookie to visitor's browser and http.SetCookie() example
+8.2k How to show different content from website server when AdBlock is detected?
+12.2k Golang : Detect user location with HTML5 geo-location
+4.5k Java : Generate multiplication table example
+12.8k Swift : Convert (cast) Int or int32 value to CGFloat