You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

100 lines
1.8 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. package common
  2. import (
  3. "container/heap"
  4. )
  5. type Comparable interface {
  6. Less(o interface{}) bool
  7. }
  8. //-----------------------------------------------------------------------------
  9. /*
  10. Example usage:
  11. h := NewHeap()
  12. h.Push(String("msg1"), 1)
  13. h.Push(String("msg3"), 3)
  14. h.Push(String("msg2"), 2)
  15. fmt.Println(h.Pop())
  16. fmt.Println(h.Pop())
  17. fmt.Println(h.Pop())
  18. */
  19. type Heap struct {
  20. pq priorityQueue
  21. }
  22. func NewHeap() *Heap {
  23. return &Heap{pq: make([]*pqItem, 0)}
  24. }
  25. func (h *Heap) Len() int64 {
  26. return int64(len(h.pq))
  27. }
  28. func (h *Heap) Push(value interface{}, priority Comparable) {
  29. heap.Push(&h.pq, &pqItem{value: value, priority: priority})
  30. }
  31. func (h *Heap) Peek() interface{} {
  32. if len(h.pq) == 0 {
  33. return nil
  34. }
  35. return h.pq[0].value
  36. }
  37. func (h *Heap) Pop() interface{} {
  38. item := heap.Pop(&h.pq).(*pqItem)
  39. return item.value
  40. }
  41. //-----------------------------------------------------------------------------
  42. ///////////////////////
  43. // From: http://golang.org/pkg/container/heap/#example__priorityQueue
  44. type pqItem struct {
  45. value interface{}
  46. priority Comparable
  47. index int
  48. }
  49. type priorityQueue []*pqItem
  50. func (pq priorityQueue) Len() int { return len(pq) }
  51. func (pq priorityQueue) Less(i, j int) bool {
  52. return pq[i].priority.Less(pq[j].priority)
  53. }
  54. func (pq priorityQueue) Swap(i, j int) {
  55. pq[i], pq[j] = pq[j], pq[i]
  56. pq[i].index = i
  57. pq[j].index = j
  58. }
  59. func (pq *priorityQueue) Push(x interface{}) {
  60. n := len(*pq)
  61. item := x.(*pqItem)
  62. item.index = n
  63. *pq = append(*pq, item)
  64. }
  65. func (pq *priorityQueue) Pop() interface{} {
  66. old := *pq
  67. n := len(old)
  68. item := old[n-1]
  69. item.index = -1 // for safety
  70. *pq = old[0 : n-1]
  71. return item
  72. }
  73. func (pq *priorityQueue) Update(item *pqItem, value interface{}, priority Comparable) {
  74. heap.Remove(pq, item.index)
  75. item.value = value
  76. item.priority = priority
  77. heap.Push(pq, item)
  78. }