weight.go 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. package rand
  2. import "math/rand"
  3. type (
  4. Weight[V any] struct {
  5. items []*item[V]
  6. totalScore int32
  7. }
  8. item[V any] struct {
  9. value V
  10. score int32
  11. }
  12. )
  13. func NewSliceWeight[V any](list []V, fn func(V) int32) *Weight[V] {
  14. weight := &Weight[V]{}
  15. for _, v := range list {
  16. score := fn(v)
  17. weight.addItem(v, score)
  18. }
  19. return weight
  20. }
  21. func NewMapWeight[K comparable, V any](maps map[K]V, fn func(V) int32) *Weight[V] {
  22. weight := &Weight[V]{}
  23. for _, v := range maps {
  24. score := fn(v)
  25. weight.addItem(v, score)
  26. }
  27. return weight
  28. }
  29. func (p *Weight[V]) addItem(v V, score int32) {
  30. if score < 1 {
  31. // pass
  32. return
  33. }
  34. p.totalScore += score
  35. p.items = append(p.items, &item[V]{
  36. value: v,
  37. score: p.totalScore,
  38. })
  39. }
  40. func (p *Weight[V]) SelectOne() (v V) {
  41. if p.totalScore < 1 {
  42. return
  43. }
  44. randScore := rand.Int31n(p.totalScore)
  45. for _, row := range p.items {
  46. if row.score >= randScore {
  47. return row.value
  48. }
  49. }
  50. return
  51. }
  52. func (p *Weight[V]) Select(count int) []V {
  53. if p.totalScore < 1 {
  54. return nil
  55. }
  56. s := make([]V, count)
  57. for i := range count {
  58. randScore := rand.Int31n(p.totalScore)
  59. for _, row := range p.items {
  60. if row.score >= randScore {
  61. s[i] = row.value
  62. break
  63. }
  64. }
  65. }
  66. return s
  67. }
  68. func (p *Weight[V]) All() []V {
  69. s := make([]V, len(p.items))
  70. for i, row := range p.items {
  71. s[i] = row.value
  72. }
  73. return s
  74. }
  75. func (p *Weight[V]) SelectIfPresent() (v V, ok bool) {
  76. if p.totalScore < 1 {
  77. return
  78. }
  79. randScore := rand.Int31n(p.totalScore)
  80. for _, row := range p.items {
  81. if row.score >= randScore {
  82. return row.value, true
  83. }
  84. }
  85. return
  86. }
  87. func (p *Weight[V]) TotalScore() int32 {
  88. return p.totalScore
  89. }
  90. func SelectMapping[V any, I any](p *Weight[V], num int32, mapper func(V) (I, bool)) []I {
  91. if mapper == nil {
  92. return []I{}
  93. }
  94. s := []I{}
  95. for i := int32(0); i < num; i++ {
  96. if mapValue, ok := mapper(p.SelectOne()); ok {
  97. s = append(s, mapValue)
  98. }
  99. }
  100. return s
  101. }
  102. // SelectUnique 选择不重复的元素,当请求数量大于可用元素数量时返回所有元素
  103. func (p *Weight[V]) SelectUnique(count int) []V {
  104. if p.totalScore < 1 {
  105. return nil
  106. }
  107. item_count := len(p.items)
  108. if count <= 0 {
  109. return []V{}
  110. }
  111. // 如果请求数量大于等于元素数量,直接返回所有元素
  112. if count >= item_count {
  113. return p.All()
  114. }
  115. // 创建副本以避免修改原始数据
  116. remainingItems := make([]*item[V], item_count)
  117. copy(remainingItems, p.items)
  118. result := make([]V, 0, count)
  119. for i := 0; i < count && len(remainingItems) > 0; i++ {
  120. remainingTotal := calculateTotalScore(remainingItems)
  121. randScore := rand.Int31n(remainingTotal)
  122. // 在剩余元素中查找
  123. selectedIndex := -1
  124. for idx, row := range remainingItems {
  125. if row.score >= randScore {
  126. selectedIndex = idx
  127. result = append(result, row.value)
  128. break
  129. }
  130. }
  131. if selectedIndex >= 0 {
  132. // 移除已选中的元素
  133. remainingItems = append(remainingItems[:selectedIndex], remainingItems[selectedIndex+1:]...)
  134. // 更新后续元素的分数
  135. updateScores(remainingItems, selectedIndex)
  136. }
  137. }
  138. return result
  139. }
  140. // 计算剩余元素的总分数
  141. func calculateTotalScore[V any](items []*item[V]) int32 {
  142. if len(items) == 0 {
  143. return 0
  144. }
  145. return items[len(items)-1].score
  146. }
  147. // 更新从指定位置开始的元素分数
  148. func updateScores[V any](items []*item[V], startIdx int) {
  149. var prevScore int32
  150. if startIdx > 0 {
  151. prevScore = items[startIdx-1].score
  152. } else {
  153. prevScore = 0
  154. }
  155. for i := startIdx; i < len(items); i++ {
  156. // 计算该项的实际分数值(与前一元素的差值)
  157. actualScore := items[i].score
  158. if i > 0 {
  159. actualScore -= items[i-1].score
  160. }
  161. // 更新累计分数
  162. prevScore += actualScore
  163. items[i].score = prevScore
  164. }
  165. }