生成随机数(纠错)
go标准库:我在其中并没有找到一定要加随机种子的字样
我在其中并没有找到一定要加随机种子的字样
下面这段代码看似随机,但生成就会发现每次都是固定的值
为什么没有产生随机的效果呢?
程序的运行环境是固定的,因此 rand.Intn 总是会返回相同的数字。 (要得到不同的数字,需为生成器提供不同的种子数)
// 这里使用的是“math/rand”
import "math/rand"
func RandInt(min, max int) int {
if min >= max || min == 0 || max == 0 {
return max
}
return rand.Intn(max-min) + min
}
改正
import "math/rand"
func RandInt(min, max int) int {
if min >= max || min == 0 || max == 0 {
return max
}
rand.Seed(time.Now().Unix())
return rand.Intn(max-min) + min
}
根据数组长度生成随机索引
0 第一种
reasons := []string{"85", "89", "45"}
s := mrand.NewSource(time.Now().Unix())
r := mrand.New(s) // initialize local pseudorandom generator
intn := r.Intn(len(reasons))
fmt.Println(intn)
1 第二种
rand.Seed(time.Now().Unix())
mid := codeImei[rand.Intn(len(reasons))]
生成指定长度随机数
import "crypto/rand"
// 注意此处的rand是crypto包下的
func CreateRandomNumber(len int) string{
var numbers = []byte{1,2,3,4,5,7,8,9}
var container string
length := bytes.NewReader(numbers).Len()
for i:=1;i<=len;i++{
random,err := rand.Int(rand.Reader,big.NewInt(int64(length)))
if err != nil {
}
container += fmt.Sprintf("%d",numbers[random.Int64()])
}
return container
}
生成随机字符串(随机密码)
import (
"math/big"
"bytes"
"crypto/rand"
"github.com/go-ffmt/ffmt"
)
func main() {
randomStr := CreateRandomString(15)
ffmt.P(randomStr)
//string("mCvYEd8MH8xnBRn")
}
func CreateRandomString(len int) string {
var container string
var str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
b := bytes.NewBufferString(str)
length := b.Len()
bigInt := big.NewInt(int64(length))
for i := 0;i < len ;i++ {
randomInt,_ := rand.Int(rand.Reader,bigInt)
container += string(str[randomInt.Int64()])
}
return container
}
从数组中随机选择
// 此处用的是math/rand
codeImei := []string{"80", "81", "37", "40", "62", "61"}
rand.Seed(time.Now().Unix())
mid := codeImei[rand.Intn(len(codeImei))]
加权随机
import (
/* ...snip... */
wr "github.com/mroth/weightedrand"
)
func main() {
rand.Seed(time.Now().UTC().UnixNano()) // always seed random!
chooser, _ := wr.NewChooser(
wr.Choice{Item: "🍒", Weight: 0},
wr.Choice{Item: "🍋", Weight: 1},
wr.Choice{Item: "🍊", Weight: 1},
wr.Choice{Item: "🍉", Weight: 3},
wr.Choice{Item: "🥑", Weight: 5},
)
/* The following will print 🍋 and 🍊 with 0.1 probability, 🍉 with 0.3
probability, and 🥑 with 0.5 probability. 🍒 will never be printed. (Note
the weights don't have to add up to 10, that was just done here to make the
example easier to read.) */
result := chooser.Pick().(string)
fmt.Println(result)
}