rank.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package service
  2. import (
  3. "context"
  4. "sort"
  5. "sync"
  6. "go-common/app/job/main/figure-timer/model"
  7. "go-common/library/log"
  8. )
  9. var (
  10. rank = &scores{}
  11. )
  12. type scores struct {
  13. ss []int32
  14. mu sync.Mutex
  15. }
  16. func (s *scores) AddScore(score int32) {
  17. s.mu.Lock()
  18. defer s.mu.Unlock()
  19. s.ss = append(s.ss, score)
  20. }
  21. func (s *scores) Init() {
  22. s.ss = make([]int32, 0)
  23. }
  24. func (s *scores) Sort() {
  25. sort.Sort(s)
  26. }
  27. func (s *scores) Get(i int) int32 {
  28. return s.ss[i]
  29. }
  30. func (s *scores) Len() int {
  31. return len(s.ss)
  32. }
  33. func (s *scores) Less(i1, i2 int) bool {
  34. return s.ss[i1] > s.ss[i2]
  35. }
  36. func (s *scores) Swap(i1, i2 int) {
  37. s.ss[i1], s.ss[i2] = s.ss[i2], s.ss[i1]
  38. }
  39. func (s *Service) calcRank(c context.Context, ver int64) {
  40. if rank.Len() <= 0 {
  41. return
  42. }
  43. rank.Sort()
  44. var (
  45. scoreFrom, scoreTo int32
  46. err error
  47. )
  48. scoreTo = rank.Get(0)
  49. for i := int8(1); i <= 100; i++ {
  50. var index int
  51. if i == 100 {
  52. scoreFrom = 0
  53. } else {
  54. index = int(float64(rank.Len()) * (float64(i) / 100.0))
  55. scoreFrom = rank.Get(index)
  56. }
  57. if scoreFrom > scoreTo {
  58. scoreTo = scoreFrom
  59. }
  60. r := &model.Rank{ScoreFrom: scoreFrom, ScoreTo: scoreTo, Percentage: i, Ver: ver}
  61. if _, err = s.dao.InsertRankHistory(c, r); err != nil {
  62. log.Error("%+v", err)
  63. return
  64. }
  65. if _, err = s.dao.UpsertRank(c, r); err != nil {
  66. log.Error("%+v", err)
  67. return
  68. }
  69. scoreTo = scoreFrom - 1
  70. }
  71. }