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.

87 lines
1.6 KiB

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