trend_heap.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. package service
  2. import (
  3. "container/heap"
  4. "go-common/app/job/main/up-rating/model"
  5. )
  6. // Heap for diff topK
  7. type Heap interface {
  8. Put(*model.Diff)
  9. Result() []*model.Diff
  10. }
  11. // AscHeap for asc
  12. type AscHeap struct {
  13. heap []*model.Diff
  14. ctype int
  15. }
  16. // Put put diff to heap
  17. func (a *AscHeap) Put(diff *model.Diff) {
  18. heap.Push(a, diff)
  19. if a.Len() > 200 {
  20. heap.Pop(a)
  21. }
  22. }
  23. // Result get result
  24. func (a *AscHeap) Result() []*model.Diff {
  25. return a.heap
  26. }
  27. // Len len
  28. func (a *AscHeap) Len() int { return len(a.heap) }
  29. // Less less
  30. func (a *AscHeap) Less(i, j int) bool {
  31. return a.heap[i].GetScore(a.ctype) < a.heap[j].GetScore(a.ctype)
  32. }
  33. // Swap swap
  34. func (a *AscHeap) Swap(i, j int) { a.heap[i], a.heap[j] = a.heap[j], a.heap[i] }
  35. // Push push to heap
  36. func (a *AscHeap) Push(x interface{}) {
  37. a.heap = append(a.heap, x.(*model.Diff))
  38. }
  39. // Pop pop from heap
  40. func (a *AscHeap) Pop() interface{} {
  41. old := a.heap
  42. n := len(old)
  43. x := old[n-1]
  44. a.heap = old[0 : n-1]
  45. return x
  46. }
  47. // DescHeap for desc
  48. type DescHeap struct {
  49. heap []*model.Diff
  50. ctype int
  51. }
  52. // Put to descHeap
  53. func (d *DescHeap) Put(diff *model.Diff) {
  54. heap.Push(d, diff)
  55. if d.Len() > 200 {
  56. heap.Pop(d)
  57. }
  58. }
  59. // Result desc heap result
  60. func (d *DescHeap) Result() []*model.Diff {
  61. return d.heap
  62. }
  63. // Len len
  64. func (d *DescHeap) Len() int { return len(d.heap) }
  65. // Less less
  66. func (d *DescHeap) Less(i, j int) bool {
  67. return d.heap[i].GetScore(d.ctype) > d.heap[j].GetScore(d.ctype)
  68. }
  69. // Swap swap
  70. func (d *DescHeap) Swap(i, j int) { d.heap[i], d.heap[j] = d.heap[j], d.heap[i] }
  71. // Push push to desc heap
  72. func (d *DescHeap) Push(x interface{}) {
  73. d.heap = append(d.heap, x.(*model.Diff))
  74. }
  75. // Pop pop from desc heap
  76. func (d *DescHeap) Pop() interface{} {
  77. old := d.heap
  78. n := len(old)
  79. x := old[n-1]
  80. d.heap = old[0 : n-1]
  81. return x
  82. }