weighted_select.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. // Copyright 2016 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package utils
  17. import "math/rand"
  18. // wrsItem interface should be implemented by any entries that are to be selected from
  19. // a WeightedRandomSelect set. Note that recalculating monotonously decreasing item
  20. // weights on-demand (without constantly calling Update) is allowed
  21. type wrsItem interface {
  22. Weight() int64
  23. }
  24. // WeightedRandomSelect is capable of weighted random selection from a set of items
  25. type WeightedRandomSelect struct {
  26. root *wrsNode
  27. idx map[wrsItem]int
  28. }
  29. // NewWeightedRandomSelect returns a new WeightedRandomSelect structure
  30. func NewWeightedRandomSelect() *WeightedRandomSelect {
  31. return &WeightedRandomSelect{root: &wrsNode{maxItems: wrsBranches}, idx: make(map[wrsItem]int)}
  32. }
  33. // setWeight sets an item's weight to a specific value (removes it if zero)
  34. func (w *WeightedRandomSelect) setWeight(item wrsItem, weight int64) {
  35. idx, ok := w.idx[item]
  36. if ok {
  37. w.root.setWeight(idx, weight)
  38. if weight == 0 {
  39. delete(w.idx, item)
  40. }
  41. } else {
  42. if weight != 0 {
  43. if w.root.itemCnt == w.root.maxItems {
  44. // add a new level
  45. newRoot := &wrsNode{sumWeight: w.root.sumWeight, itemCnt: w.root.itemCnt, level: w.root.level + 1, maxItems: w.root.maxItems * wrsBranches}
  46. newRoot.items[0] = w.root
  47. newRoot.weights[0] = w.root.sumWeight
  48. w.root = newRoot
  49. }
  50. w.idx[item] = w.root.insert(item, weight)
  51. }
  52. }
  53. }
  54. // Update updates an item's weight, adds it if it was non-existent or removes it if
  55. // the new weight is zero. Note that explicitly updating decreasing weights is not necessary.
  56. func (w *WeightedRandomSelect) Update(item wrsItem) {
  57. w.setWeight(item, item.Weight())
  58. }
  59. // Remove removes an item from the set
  60. func (w *WeightedRandomSelect) Remove(item wrsItem) {
  61. w.setWeight(item, 0)
  62. }
  63. // Choose randomly selects an item from the set, with a chance proportional to its
  64. // current weight. If the weight of the chosen element has been decreased since the
  65. // last stored value, returns it with a newWeight/oldWeight chance, otherwise just
  66. // updates its weight and selects another one
  67. func (w *WeightedRandomSelect) Choose() wrsItem {
  68. for {
  69. if w.root.sumWeight == 0 {
  70. return nil
  71. }
  72. val := rand.Int63n(w.root.sumWeight)
  73. choice, lastWeight := w.root.choose(val)
  74. weight := choice.Weight()
  75. if weight != lastWeight {
  76. w.setWeight(choice, weight)
  77. }
  78. if weight >= lastWeight || rand.Int63n(lastWeight) < weight {
  79. return choice
  80. }
  81. }
  82. }
  83. const wrsBranches = 8 // max number of branches in the wrsNode tree
  84. // wrsNode is a node of a tree structure that can store wrsItems or further wrsNodes.
  85. type wrsNode struct {
  86. items [wrsBranches]interface{}
  87. weights [wrsBranches]int64
  88. sumWeight int64
  89. level, itemCnt, maxItems int
  90. }
  91. // insert recursively inserts a new item to the tree and returns the item index
  92. func (n *wrsNode) insert(item wrsItem, weight int64) int {
  93. branch := 0
  94. for n.items[branch] != nil && (n.level == 0 || n.items[branch].(*wrsNode).itemCnt == n.items[branch].(*wrsNode).maxItems) {
  95. branch++
  96. if branch == wrsBranches {
  97. panic(nil)
  98. }
  99. }
  100. n.itemCnt++
  101. n.sumWeight += weight
  102. n.weights[branch] += weight
  103. if n.level == 0 {
  104. n.items[branch] = item
  105. return branch
  106. }
  107. var subNode *wrsNode
  108. if n.items[branch] == nil {
  109. subNode = &wrsNode{maxItems: n.maxItems / wrsBranches, level: n.level - 1}
  110. n.items[branch] = subNode
  111. } else {
  112. subNode = n.items[branch].(*wrsNode)
  113. }
  114. subIdx := subNode.insert(item, weight)
  115. return subNode.maxItems*branch + subIdx
  116. }
  117. // setWeight updates the weight of a certain item (which should exist) and returns
  118. // the change of the last weight value stored in the tree
  119. func (n *wrsNode) setWeight(idx int, weight int64) int64 {
  120. if n.level == 0 {
  121. oldWeight := n.weights[idx]
  122. n.weights[idx] = weight
  123. diff := weight - oldWeight
  124. n.sumWeight += diff
  125. if weight == 0 {
  126. n.items[idx] = nil
  127. n.itemCnt--
  128. }
  129. return diff
  130. }
  131. branchItems := n.maxItems / wrsBranches
  132. branch := idx / branchItems
  133. diff := n.items[branch].(*wrsNode).setWeight(idx-branch*branchItems, weight)
  134. n.weights[branch] += diff
  135. n.sumWeight += diff
  136. if weight == 0 {
  137. n.itemCnt--
  138. }
  139. return diff
  140. }
  141. // Choose recursively selects an item from the tree and returns it along with its weight
  142. func (n *wrsNode) choose(val int64) (wrsItem, int64) {
  143. for i, w := range n.weights {
  144. if val < w {
  145. if n.level == 0 {
  146. return n.items[i].(wrsItem), n.weights[i]
  147. }
  148. return n.items[i].(*wrsNode).choose(val)
  149. }
  150. val -= w
  151. }
  152. panic(nil)
  153. }