random.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package common
  2. import (
  3. "errors"
  4. "math/rand"
  5. "time"
  6. )
  7. const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  8. const (
  9. letterIdxBits = 6 // 6 bits to represent a letter index
  10. letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits
  11. letterIdxMax = 63 / letterIdxBits // # of letter indices fitting in 63 bits
  12. )
  13. func GenRandomString(n int) string {
  14. rand.Seed(time.Now().UnixNano())
  15. var src = rand.NewSource(time.Now().UnixNano())
  16. b := make([]byte, n)
  17. // A src.Int63() generates 63 random bits, enough for letterIdxMax characters!
  18. for i, cache, remain := n-1, src.Int63(), letterIdxMax; i >= 0; {
  19. if remain == 0 {
  20. cache, remain = src.Int63(), letterIdxMax
  21. }
  22. if idx := int(cache & letterIdxMask); idx < len(letterBytes) {
  23. b[i] = letterBytes[idx]
  24. i--
  25. }
  26. cache >>= letterIdxBits
  27. remain--
  28. }
  29. return string(b)
  30. }
  31. func RandomStrArr(arr []string, length int) error {
  32. rand.Seed(time.Now().UnixNano())
  33. if len(arr) <= 0 {
  34. return errors.New("the length of the parameter strings should not be less than 0")
  35. }
  36. if length <= 0 || len(arr) < length {
  37. return errors.New("the size of the parameter length illegal")
  38. }
  39. for i := len(arr) - 1; i > 0; i-- {
  40. num := rand.Intn(i + 1)
  41. arr[i], arr[num] = arr[num], arr[i]
  42. }
  43. return nil
  44. }
  45. func GetRandNumber(num int) int {
  46. rand.Seed(time.Now().UnixNano())
  47. if num == 0 {
  48. return 0
  49. }
  50. res := rand.Intn(num)
  51. if res < 0 {
  52. return -res
  53. }
  54. return res
  55. }
  56. func GetRandNumberInt64(num int64) int64 {
  57. rand.Seed(time.Now().UnixNano())
  58. if num == 0 {
  59. return 0
  60. }
  61. res := rand.Int63n(num)
  62. if res < 0 {
  63. return -res
  64. }
  65. return res
  66. }