prque.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. // Package prque implements a priority queue data structure supporting arbitrary
  9. // value types and float priorities.
  10. //
  11. // The reasoning behind using floats for the priorities vs. ints or interfaces
  12. // was larger flexibility without sacrificing too much performance or code
  13. // complexity.
  14. //
  15. // If you would like to use a min-priority queue, simply negate the priorities.
  16. //
  17. // Internally the queue is based on the standard heap package working on a
  18. // sortable version of the block based stack.
  19. package prque
  20. import (
  21. "container/heap"
  22. )
  23. // Priority queue data structure.
  24. type Prque struct {
  25. cont *sstack
  26. }
  27. // Creates a new priority queue.
  28. func New() *Prque {
  29. return &Prque{newSstack()}
  30. }
  31. // Pushes a value with a given priority into the queue, expanding if necessary.
  32. func (p *Prque) Push(data interface{}, priority float32) {
  33. heap.Push(p.cont, &item{data, priority})
  34. }
  35. // Pops the value with the greates priority off the stack and returns it.
  36. // Currently no shrinking is done.
  37. func (p *Prque) Pop() (interface{}, float32) {
  38. item := heap.Pop(p.cont).(*item)
  39. return item.value, item.priority
  40. }
  41. // Pops only the item from the queue, dropping the associated priority value.
  42. func (p *Prque) PopItem() interface{} {
  43. return heap.Pop(p.cont).(*item).value
  44. }
  45. // Checks whether the priority queue is empty.
  46. func (p *Prque) Empty() bool {
  47. return p.cont.Len() == 0
  48. }
  49. // Returns the number of element in the priority queue.
  50. func (p *Prque) Size() int {
  51. return p.cont.Len()
  52. }
  53. // Clears the contents of the priority queue.
  54. func (p *Prque) Reset() {
  55. *p = *New()
  56. }