prque.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // CookieJar - A contestant's algorithm toolbox
  2. // Copyright (c) 2013 Peter Szilagyi. All rights reserved.
  3. //
  4. // CookieJar is dual licensed: use of this source code is governed by a BSD
  5. // license that can be found in the LICENSE file. Alternatively, the CookieJar
  6. // toolbox may be used in accordance with the terms and conditions contained
  7. // in a signed written agreement between you and the author(s).
  8. // This is a duplicated and slightly modified version of "gopkg.in/karalabe/cookiejar.v2/collections/prque".
  9. // Package prque implements a priority queue data structure supporting arbitrary
  10. // value types and int64 priorities.
  11. //
  12. // If you would like to use a min-priority queue, simply negate the priorities.
  13. //
  14. // Internally the queue is based on the standard heap package working on a
  15. // sortable version of the block based stack.
  16. package prque
  17. import (
  18. "container/heap"
  19. )
  20. // Priority queue data structure.
  21. type Prque struct {
  22. cont *sstack
  23. }
  24. // New creates a new priority queue.
  25. func New(setIndex SetIndexCallback) *Prque {
  26. return &Prque{newSstack(setIndex)}
  27. }
  28. // Pushes a value with a given priority into the queue, expanding if necessary.
  29. func (p *Prque) Push(data interface{}, priority int64) {
  30. heap.Push(p.cont, &item{data, priority})
  31. }
  32. // Peek returns the value with the greates priority but does not pop it off.
  33. func (p *Prque) Peek() (interface{}, int64) {
  34. item := p.cont.blocks[0][0]
  35. return item.value, item.priority
  36. }
  37. // Pops the value with the greates priority off the stack and returns it.
  38. // Currently no shrinking is done.
  39. func (p *Prque) Pop() (interface{}, int64) {
  40. item := heap.Pop(p.cont).(*item)
  41. return item.value, item.priority
  42. }
  43. // Pops only the item from the queue, dropping the associated priority value.
  44. func (p *Prque) PopItem() interface{} {
  45. return heap.Pop(p.cont).(*item).value
  46. }
  47. // Remove removes the element with the given index.
  48. func (p *Prque) Remove(i int) interface{} {
  49. if i < 0 {
  50. return nil
  51. }
  52. return heap.Remove(p.cont, i)
  53. }
  54. // Checks whether the priority queue is empty.
  55. func (p *Prque) Empty() bool {
  56. return p.cont.Len() == 0
  57. }
  58. // Returns the number of element in the priority queue.
  59. func (p *Prque) Size() int {
  60. return p.cont.Len()
  61. }
  62. // Clears the contents of the priority queue.
  63. func (p *Prque) Reset() {
  64. *p = *New(p.cont.setIndex)
  65. }