Create Random number & Pure Random Number in Golang

Create Random number & Pure Random Number in Golang

1. Create Random number Using math/rand

Package rand implements pseudo-random number generators unsuitable for security-sensitive work.

Random numbers are generated by a Source. Top-level functions, such as Float64 and Int, use a default shared Source that produces a deterministic sequence of values each time a program is run. Use the Seed function to initialize the default Source if different behavior is required for each run. The default Source is safe for concurrent use by multiple goroutines, but Sources created by NewSource are not.

This package's outputs might be easily predictable regardless of how it's seeded. For random numbers suitable for security-sensitive work, see the crypto/rand package.

package  main

import (
    "fmt"
    "math/rand"
    "time"

)

func main(){
    RandomIntWithOutSeed()
    RandomInt()
    RandomIntn()

    RandomFloatWithOutSeed()
    RandomFloar64()

    RandomPerm()// generate a list of random int number
}

Generate Integer without using Seed

func RandomIntWithOutSeed(){
    s:= rand.Int()
    fmt.Printf("##  Random Integer without Seed \n{rand.Int()} : %d \n\n",s)
}

Generate Integer using Seed

func RandomInt(){
    rand.Seed(time.Now().UnixNano())
    s:= rand.Int()
    fmt.Printf("##  Random Integer with Seed \n{rand.Int()} : %d \n\n",s)
}

Generate Integer in a given range using Seed

func RandomIntn(){
    rand.Seed(time.Now().UnixNano())
    min:=10
    max:=20
    //s:= rand.Intn(100)
    s:= rand.Intn(max-min)+min
    fmt.Printf("##  Random Integer with Seed with Number Range\n{rand.Intn(max-min)+min} : %d\n\n",s)
}

Generate Float Number without using Seed

func RandomFloatWithOutSeed(){
    s:=rand.Float64()
    fmt.Printf("##  Random Float without Seed \n{rand.Float64()} : %f\n\n",s)
}

Generate Float Number using Seed

func RandomFloar64(){
    rand.Seed(time.Now().UnixNano())
    s:=rand.Float64()
    fmt.Printf("##  Random Float with Seed \n{rand.Float64()} : %f\n\n",s)
}

Generate Integer Number using Seed and parameter

func RandomPerm(){
    rand.Seed(time.Now().UnixNano())
    s:=rand.Perm(10)
    fmt.Printf("## Random List of Integer Number \n{rand.Perm(n) : %v\n\n",s)
}

2. Write Pure Random number using crypto/rand

Package rand implements a cryptographically secure random number generator.

package main

import (
    "fmt"
    "crypto/rand"
    "math/big"
)

func main() {
    nBig, err := rand.Int(rand.Reader, big.NewInt(27))
    if err != nil {
        panic(err)
    }
    n := nBig.Int64()
    fmt.Printf("Here is a random %T in [0,27) : %d\n", n, n)
}