2025-05-25 20:02:15 +08:00
|
|
|
package xrand
|
|
|
|
|
|
|
|
import (
|
|
|
|
"math/rand"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2025-05-26 16:02:54 +08:00
|
|
|
var rd *rand.Rand
|
|
|
|
|
2025-05-25 20:02:15 +08:00
|
|
|
func init() {
|
2025-05-26 16:02:54 +08:00
|
|
|
rd = rand.New(rand.NewSource(time.Now().UnixNano()))
|
2025-05-25 20:02:15 +08:00
|
|
|
}
|
|
|
|
|
2025-06-08 17:59:35 +08:00
|
|
|
// 随机值
|
|
|
|
func Rand[T int | int32 | int64 | uint32 | uint64 | float32 | float64]() T {
|
|
|
|
switch any(T(0)).(type) {
|
|
|
|
case int:
|
|
|
|
return T(rd.Int())
|
|
|
|
case int32:
|
|
|
|
return T(rd.Int31())
|
|
|
|
case int64:
|
|
|
|
return T(rd.Int63())
|
|
|
|
case uint32:
|
|
|
|
return T(rd.Uint32())
|
|
|
|
case uint64:
|
|
|
|
return T(rd.Uint64())
|
|
|
|
case float32:
|
|
|
|
return T(rd.Float32())
|
|
|
|
case float64:
|
|
|
|
return T(rd.Float64())
|
|
|
|
default:
|
|
|
|
panic("不支持的类型")
|
|
|
|
}
|
2025-05-25 20:02:15 +08:00
|
|
|
}
|
|
|
|
|
2025-06-08 17:59:35 +08:00
|
|
|
// 从[0,n)范围里随机值
|
|
|
|
func RandN[T int | int32 | int64 | uint32 | uint64](n T) T {
|
|
|
|
if int64(n) < 1 {
|
|
|
|
return 0
|
|
|
|
}
|
|
|
|
switch any(n).(type) {
|
|
|
|
case int:
|
|
|
|
return T(rd.Intn(int(n))) // [0,n) 的随机整数
|
|
|
|
case int32:
|
|
|
|
return T(rd.Int31n(int32(n)))
|
|
|
|
case int64:
|
|
|
|
return T(rd.Int63n(int64(n)))
|
|
|
|
case uint32:
|
|
|
|
return T(rd.Uint32() % uint32(n)) // 注意:这里有小偏差
|
|
|
|
case uint64:
|
|
|
|
return T(rand.Uint64() % uint64(n))
|
|
|
|
default:
|
|
|
|
panic("不支持的类型")
|
|
|
|
}
|
2025-05-25 20:02:15 +08:00
|
|
|
}
|
|
|
|
|
2025-06-08 17:59:35 +08:00
|
|
|
// 从[0,n)范围里随机值
|
|
|
|
func RandRange[T int | int32 | int64 | uint32 | uint64](min, max T) T {
|
|
|
|
if int64(max) < 1 || int64(min) < 1 || max < min {
|
|
|
|
return 0
|
|
|
|
}
|
|
|
|
return RandN[T](max-min) + min
|
2025-05-25 20:02:15 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func Perm(n int) []int {
|
2025-05-26 16:02:54 +08:00
|
|
|
return rd.Perm(n)
|
2025-05-25 20:02:15 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func Read(p []byte) (n int, err error) {
|
2025-05-26 16:02:54 +08:00
|
|
|
return rd.Read(p)
|
2025-05-25 20:02:15 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func Shuffle[T any](slice []T) {
|
|
|
|
rand.Shuffle(len(slice), func(i, j int) {
|
|
|
|
slice[i], slice[j] = slice[j], slice[i]
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2025-06-06 00:09:35 +08:00
|
|
|
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
|
|
|
|
|
|
|
func RandomString(n int) string {
|
|
|
|
b := make([]byte, n)
|
|
|
|
for i := range b {
|
|
|
|
b[i] = letterBytes[rd.Intn(len(letterBytes))]
|
|
|
|
}
|
|
|
|
return string(b)
|
|
|
|
}
|