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
+13.4k Golang : Generate Code128 barcode
+18.4k Golang : How to remove certain lines from a file
+11.6k Golang : Convert(cast) float to int
+19.9k Golang : Accept input from user with fmt.Scanf skipped white spaces and how to fix it
+17.9k Golang : Login and logout a user after password verification and redirect example
+9.8k Golang : Format strings to SEO friendly URL example
+5.9k Golang : Generate multiplication table from an integer example
+24.5k Golang : Time slice or date sort and reverse sort example
+13.6k Golang : Set image canvas or background to transparent
+31.9k Golang : Convert an image file to []byte
+9.4k Golang : Create unique title slugs example
+7.9k Setting $GOPATH environment variable for Unix/Linux and Windows