C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
So: The program generates the same numbers each time. Try running it multiple times—it always has the same result.
Int: This method returns a positive (non-negative) int. No fractional or negative values are possible.
Tip: To change the initial series of values returned by rand.Int, use the Seed method.
Golang program that uses rand.Int
package main
import (
"fmt"
"math/rand"
)
func main() {
// Loop five times.
for i := 0; i < 5; i++ {
// Get random positive integer.
value := rand.Int()
fmt.Println(value)
}
}
Output
5577006791947779410
8674665223082153551
6129484611666145821
4037200794235010051
3916589616287113937
Here: We use the current Nanoseconds from the time. We cast this to an int64 to seed the number generator.
TimeNote: If you run this program many times, each execution will print a different random number.
Golang program that uses Seed
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
// Call Seed, using current nanoseconds.
rand.Seed(int64(time.Now().Nanosecond()))
// Random int will be different each program execution.
value := rand.Int()
fmt.Println(value)
}
Output
6912970929678809162
Here: We call rand.Perm with an argument of 5. So the numbers 0, 1, 2, 3, and 4 are randomly arranged in slices of 5 elements.
Important: Perm uses the default random source. So we would need to use Seed to avoid the same output on each program run.
Golang program that uses rand.Perm
package main
import (
"fmt"
"math/rand"
)
func main() {
for i := 0; i < 5; i++ {
// Use rand.Perm to generate a random array of numbers.
numbers := rand.Perm(5)
fmt.Println(numbers)
}
}
Output
[0 4 2 3 1]
[4 1 2 0 3]
[2 3 0 4 1]
[0 4 2 1 3]
[1 0 4 2 3]
Program: We call the rand.Int method in "crypto/rand" 20 times. We get values that are from 0 to 99 inclusive (we never get 100).
Golang program that uses crypto rand
package main
import (
"crypto/rand"
"math/big"
"fmt"
)
func main() {
// Generate 20 random numbers with exclusive max of 100.
// ... So max value returned is 99.
// All values returned are 0 or greater as well.
for i := 0; i < 20; i++ {
result, _ := rand.Int(rand.Reader, big.NewInt(100))
fmt.Println(result)
}
}
Output
54
77
56
21
56
81
55
16
57
88
95
58
12
74
23
35
72
29
25
68
Note: The programs in this example set should all use rand.Seed for optimally random behavior.
Quote: Use the Seed function to initialize the default Source if different behavior is required for each run.
Rand: golang.org