广告平台(站长使用)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

rand.go 1.2 KiB

4 months ago
2 months ago
4 months ago
4 months ago
4 months ago
4 months ago
3 months ago
4 months ago
3 months ago
4 months ago
2 months ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package utils
  2. import (
  3. crand "crypto/rand"
  4. "fmt"
  5. "math"
  6. "math/big"
  7. "math/rand"
  8. "strconv"
  9. "time"
  10. )
  11. func RandString(l int, c ...string) string {
  12. var (
  13. chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
  14. str string
  15. num *big.Int
  16. )
  17. if len(c) > 0 {
  18. chars = c[0]
  19. }
  20. chrLen := int64(len(chars))
  21. for len(str) < l {
  22. num, _ = crand.Int(crand.Reader, big.NewInt(chrLen))
  23. str += string(chars[num.Int64()])
  24. }
  25. return str
  26. }
  27. func RandNum() string {
  28. seed := time.Now().UnixNano() + rand.Int63()
  29. return fmt.Sprintf("%05v", rand.New(rand.NewSource(seed)).Int31n(1000000))
  30. }
  31. func GenerateUniqueRandomNumbers(n int) string {
  32. rand.Seed(time.Now().UnixNano() + rand.Int63()) // 初始化随机种子
  33. numbers := make([]int, 0, n) // 创建一个切片来保存随机数,初始容量为n
  34. used := make(map[int]bool) // 跟踪已使用的数字
  35. for len(numbers) < n {
  36. b := rand.Intn(10) // 生成0-9之间的随机数
  37. if !used[b] {
  38. numbers = append(numbers, b)
  39. used[b] = true
  40. }
  41. }
  42. var numbersStr string
  43. for _, v := range numbers {
  44. numbersStr += strconv.Itoa(v)
  45. }
  46. return numbersStr
  47. }
  48. func RoundToTwoDecimalPlaces(num float64) float64 {
  49. return math.Round(num*100) / 100
  50. }