|
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253 |
- package utils
-
- import (
- crand "crypto/rand"
- "fmt"
- "math/big"
- "math/rand"
- "strconv"
- "time"
- )
-
- func RandString(l int, c ...string) string {
- var (
- chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
- str string
- num *big.Int
- )
- if len(c) > 0 {
- chars = c[0]
- }
- chrLen := int64(len(chars))
- for len(str) < l {
- num, _ = crand.Int(crand.Reader, big.NewInt(chrLen))
- str += string(chars[num.Int64()])
- }
- return str
- }
-
- func RandNum() string {
- seed := time.Now().UnixNano() + rand.Int63()
- return fmt.Sprintf("%05v", rand.New(rand.NewSource(seed)).Int31n(1000000))
- }
- func GenerateUniqueRandomNumbers(n int) string {
- rand.Seed(time.Now().UnixNano() + rand.Int63()) // 初始化随机种子
-
- numbers := make([]int, 0, n) // 创建一个切片来保存随机数,初始容量为n
- used := make(map[int]bool) // 跟踪已使用的数字
-
- for len(numbers) < n {
- b := rand.Intn(10) // 生成0-9之间的随机数
- if !used[b] {
- numbers = append(numbers, b)
- used[b] = true
- }
- }
-
- var numbersStr string
- for _, v := range numbers {
- numbersStr += strconv.Itoa(v)
- }
-
- return numbersStr
- }
|