init.code.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. package common
  2. import (
  3. "fmt"
  4. "math/rand"
  5. "sync"
  6. )
  7. func GetCode() string {
  8. res := Example(5, 10)
  9. for i := 0; i < len(res); i++ {
  10. fmt.Println(i+1, res[i])
  11. }
  12. return res[0]
  13. }
  14. func Example(length int, max int) []string {
  15. // Seeding with the same value results in the same random sequence each run.
  16. // For different numbers, seed with a different value, such as
  17. // time.Now().UnixNano(), which yields a constantly-changing number.
  18. //rand.Seed(42)
  19. digitNumber := []string{
  20. "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
  21. }
  22. // 用make创建map
  23. set := New()
  24. for set.Len() < max {
  25. ranNumber := ""
  26. for j := 1; j < length; j++ {
  27. ranNumber += digitNumber[rand.Intn(len(digitNumber))]
  28. }
  29. if !set.Has(ranNumber) {
  30. set.Add(ranNumber)
  31. }
  32. }
  33. return set.List()
  34. }
  35. /*
  36. *
  37. 构造set类型
  38. */
  39. type Set struct {
  40. m map[string]bool
  41. sync.RWMutex
  42. }
  43. func New() *Set {
  44. return &Set{
  45. m: map[string]bool{},
  46. }
  47. }
  48. func (s *Set) Add(item string) {
  49. s.Lock()
  50. defer s.Unlock()
  51. s.m[item] = true
  52. }
  53. func (s *Set) Remove(item string) {
  54. s.Lock()
  55. s.Unlock()
  56. delete(s.m, item)
  57. }
  58. func (s *Set) Has(item string) bool {
  59. s.RLock()
  60. defer s.RUnlock()
  61. _, ok := s.m[item]
  62. return ok
  63. }
  64. func (s *Set) Len() int {
  65. return len(s.List())
  66. }
  67. func (s *Set) Clear() {
  68. s.Lock()
  69. defer s.Unlock()
  70. s.m = map[string]bool{}
  71. }
  72. func (s *Set) IsEmpty() bool {
  73. if s.Len() == 0 {
  74. return true
  75. }
  76. return false
  77. }
  78. func (s *Set) List() []string {
  79. s.RLock()
  80. defer s.RUnlock()
  81. list := []string{}
  82. for item := range s.m {
  83. list = append(list, item)
  84. }
  85. return list
  86. }