randselect.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  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 les
  17. import (
  18. "math/rand"
  19. )
  20. // wrsItem interface should be implemented by any entries that are to be selected from
  21. // a weightedRandomSelect set. Note that recalculating monotonously decreasing item
  22. // weights on-demand (without constantly calling update) is allowed
  23. type wrsItem interface {
  24. Weight() int64
  25. }
  26. // weightedRandomSelect is capable of weighted random selection from a set of items
  27. type weightedRandomSelect struct {
  28. root *wrsNode
  29. idx map[wrsItem]int
  30. }
  31. // newWeightedRandomSelect returns a new weightedRandomSelect structure
  32. func newWeightedRandomSelect() *weightedRandomSelect {
  33. return &weightedRandomSelect{root: &wrsNode{maxItems: wrsBranches}, idx: make(map[wrsItem]int)}
  34. }
  35. // update updates an item's weight, adds it if it was non-existent or removes it if
  36. // the new weight is zero. Note that explicitly updating decreasing weights is not necessary.
  37. func (w *weightedRandomSelect) update(item wrsItem) {
  38. w.setWeight(item, item.Weight())
  39. }
  40. // remove removes an item from the set
  41. func (w *weightedRandomSelect) remove(item wrsItem) {
  42. w.setWeight(item, 0)
  43. }
  44. // setWeight sets an item's weight to a specific value (removes it if zero)
  45. func (w *weightedRandomSelect) setWeight(item wrsItem, weight int64) {
  46. idx, ok := w.idx[item]
  47. if ok {
  48. w.root.setWeight(idx, weight)
  49. if weight == 0 {
  50. delete(w.idx, item)
  51. }
  52. } else {
  53. if weight != 0 {
  54. if w.root.itemCnt == w.root.maxItems {
  55. // add a new level
  56. newRoot := &wrsNode{sumWeight: w.root.sumWeight, itemCnt: w.root.itemCnt, level: w.root.level + 1, maxItems: w.root.maxItems * wrsBranches}
  57. newRoot.items[0] = w.root
  58. newRoot.weights[0] = w.root.sumWeight
  59. w.root = newRoot
  60. }
  61. w.idx[item] = w.root.insert(item, weight)
  62. }
  63. }
  64. }
  65. // choose randomly selects an item from the set, with a chance proportional to its
  66. // current weight. If the weight of the chosen element has been decreased since the
  67. // last stored value, returns it with a newWeight/oldWeight chance, otherwise just
  68. // updates its weight and selects another one
  69. func (w *weightedRandomSelect) choose() wrsItem {
  70. for {
  71. if w.root.sumWeight == 0 {
  72. return nil
  73. }
  74. val := rand.Int63n(w.root.sumWeight)
  75. choice, lastWeight := w.root.choose(val)
  76. weight := choice.Weight()
  77. if weight != lastWeight {
  78. w.setWeight(choice, weight)
  79. }
  80. if weight >= lastWeight || rand.Int63n(lastWeight) < weight {
  81. return choice
  82. }
  83. }
  84. }
  85. const wrsBranches = 8 // max number of branches in the wrsNode tree
  86. // wrsNode is a node of a tree structure that can store wrsItems or further wrsNodes.
  87. type wrsNode struct {
  88. items [wrsBranches]interface{}
  89. weights [wrsBranches]int64
  90. sumWeight int64
  91. level, itemCnt, maxItems int
  92. }
  93. // insert recursively inserts a new item to the tree and returns the item index
  94. func (n *wrsNode) insert(item wrsItem, weight int64) int {
  95. branch := 0
  96. for n.items[branch] != nil && (n.level == 0 || n.items[branch].(*wrsNode).itemCnt == n.items[branch].(*wrsNode).maxItems) {
  97. branch++
  98. if branch == wrsBranches {
  99. panic(nil)
  100. }
  101. }
  102. n.itemCnt++
  103. n.sumWeight += weight
  104. n.weights[branch] += weight
  105. if n.level == 0 {
  106. n.items[branch] = item
  107. return branch
  108. }
  109. var subNode *wrsNode
  110. if n.items[branch] == nil {
  111. subNode = &wrsNode{maxItems: n.maxItems / wrsBranches, level: n.level - 1}
  112. n.items[branch] = subNode
  113. } else {
  114. subNode = n.items[branch].(*wrsNode)
  115. }
  116. subIdx := subNode.insert(item, weight)
  117. return subNode.maxItems*branch + subIdx
  118. }
  119. // setWeight updates the weight of a certain item (which should exist) and returns
  120. // the change of the last weight value stored in the tree
  121. func (n *wrsNode) setWeight(idx int, weight int64) int64 {
  122. if n.level == 0 {
  123. oldWeight := n.weights[idx]
  124. n.weights[idx] = weight
  125. diff := weight - oldWeight
  126. n.sumWeight += diff
  127. if weight == 0 {
  128. n.items[idx] = nil
  129. n.itemCnt--
  130. }
  131. return diff
  132. }
  133. branchItems := n.maxItems / wrsBranches
  134. branch := idx / branchItems
  135. diff := n.items[branch].(*wrsNode).setWeight(idx-branch*branchItems, weight)
  136. n.weights[branch] += diff
  137. n.sumWeight += diff
  138. if weight == 0 {
  139. n.itemCnt--
  140. }
  141. return diff
  142. }
  143. // choose recursively selects an item from the tree and returns it along with its weight
  144. func (n *wrsNode) choose(val int64) (wrsItem, int64) {
  145. for i, w := range n.weights {
  146. if val < w {
  147. if n.level == 0 {
  148. return n.items[i].(wrsItem), n.weights[i]
  149. }
  150. return n.items[i].(*wrsNode).choose(val)
  151. }
  152. val -= w
  153. }
  154. panic(nil)
  155. }