Example of generating integer random Numbers using Golang


php random number

PHP is a simple way to generate a random number for a given range, and you can specify a range from negative to positive integers, such as:

<?php
echo mt_rand(-988, 888);

This generates random Numbers from -988 to 888.

Using Go is a bit of a hassle. The following two functions respectively generate a random integer in the maximum range and a random integer in the range:

Generate 1 random number in the maximum range

1 must be given a timestamp seed, otherwise each generation will have one value. Here is the random number that generates [0,100].

func GenerateRandnum() int {
 rand.Seed(time.Now().Unix())
 randNum := rand.Intn(100)
 return randNum
}

Generate 1 random number for a given range

This is really just like generating a random number 1 within a given maximum, but with a maximum and minimum range of processing.

func GenerateRangeNum(min, max int) int {
 rand.Seed(time.Now().Unix())
 randNum := rand.Intn(max - min) + min
 return randNum
}

The complete example is as follows:

func main() {
 GenerateRandnum()
 GenerateRangeNum(888, 900)
}

package main

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

// GenerateRandnum  Generate random Numbers in the maximum range
func GenerateRandnum() int {
 rand.Seed(time.Now().Unix())
 randNum := rand.Intn(100)

 fmt.Printf("rand is %v\n", randNum)

 return randNum
}

// GenerateRangeNum  generate 1 A random number within an interval
func GenerateRangeNum(min, max int) int {
  rand.Seed(time.Now().Unix())
 randNum := rand.Intn(max - min)
 randNum = randNum + min
 fmt.Printf("rand is %v\n", randNum)
 return randNum
}

func main() {
 GenerateRandnum()
 GenerateRangeNum(888, 900)
}

Operation results:

➜ examples git:(master) ✗ go run range.go

rand is 52

rand is 892

➜ examples git:(master) ✗ go run range.go

rand is 53

rand is 889

➜ examples git:(master) ✗ go run range.go

rand is 53

rand is 889

conclusion