/
random_122.go
53 lines (46 loc) · 1.1 KB
/
random_122.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
//go:build go1.22
package random
import (
"fmt"
"math/rand/v2"
"strconv"
"unsafe"
)
const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
const (
// 6 bits to represent a letter index
letterIdBits = 6
// All 1-bits as many as letterIdBits
letterIdMask = 1<<letterIdBits - 1
letterIdMax = 63 / letterIdBits
)
func RandInt(min, max int) int {
if min > max {
min, max = max, min
}
return rand.IntN(max-min) + min
}
func RandFloat64(min, max float64) float64 {
if min > max {
min, max = max, min
}
randomFloat64 := min + rand.Float64()*(max-min)
random, _ := strconv.ParseFloat(fmt.Sprintf("%.4f", randomFloat64), 64)
return random
}
func RandStr(n int) string {
b := make([]byte, n)
// A rand.Int63() generates 63 random bits, enough for letterIdMax letters!
for i, cache, remain := n-1, rand.Int64(), letterIdMax; i >= 0; {
if remain == 0 {
cache, remain = rand.Int64(), letterIdMax
}
if idx := int(cache & letterIdMask); idx < len(letters) {
b[i] = letters[idx]
i--
}
cache >>= letterIdBits
remain--
}
return *(*string)(unsafe.Pointer(&b))
}