theapqueue.nim 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. import std/heapqueue
  2. proc toSortedSeq[T](h: HeapQueue[T]): seq[T] =
  3. var tmp = h
  4. result = @[]
  5. while tmp.len > 0:
  6. result.add(pop(tmp))
  7. proc heapProperty[T](h: HeapQueue[T]): bool =
  8. for k in 0 .. h.len - 2: # the last element is always a leaf
  9. let left = 2 * k + 1
  10. if left < h.len and h[left] < h[k]:
  11. return false
  12. let right = left + 1
  13. if right < h.len and h[right] < h[k]:
  14. return false
  15. true
  16. template main() =
  17. block: # simple sanity test
  18. var heap = initHeapQueue[int]()
  19. let data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
  20. for item in data:
  21. push(heap, item)
  22. doAssert(heap == data.toHeapQueue)
  23. doAssert(heap[0] == 0)
  24. doAssert(heap.toSortedSeq == @[0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
  25. block: # test del
  26. var heap = initHeapQueue[int]()
  27. let data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
  28. for item in data: push(heap, item)
  29. heap.del(0)
  30. doAssert(heap[0] == 1)
  31. heap.del(heap.find(7))
  32. doAssert(heap.toSortedSeq == @[1, 2, 3, 4, 5, 6, 8, 9])
  33. heap.del(heap.find(5))
  34. doAssert(heap.toSortedSeq == @[1, 2, 3, 4, 6, 8, 9])
  35. heap.del(heap.find(6))
  36. doAssert(heap.toSortedSeq == @[1, 2, 3, 4, 8, 9])
  37. heap.del(heap.find(2))
  38. doAssert(heap.toSortedSeq == @[1, 3, 4, 8, 9])
  39. doAssert(heap.find(2) == -1)
  40. block: # test del last
  41. var heap = initHeapQueue[int]()
  42. let data = [1, 2, 3]
  43. for item in data: push(heap, item)
  44. heap.del(2)
  45. doAssert(heap.toSortedSeq == @[1, 2])
  46. heap.del(1)
  47. doAssert(heap.toSortedSeq == @[1])
  48. heap.del(0)
  49. doAssert(heap.toSortedSeq == @[])
  50. block: # testing the heap proeprty
  51. var heap = [1, 4, 2, 5].toHeapQueue
  52. doAssert heapProperty(heap)
  53. heap.push(42)
  54. doAssert heapProperty(heap)
  55. heap.push(0)
  56. doAssert heapProperty(heap)
  57. heap.push(3)
  58. doAssert heapProperty(heap)
  59. heap.push(3)
  60. doAssert heapProperty(heap)
  61. # [0, 3, 1, 4, 42, 2, 3, 5]
  62. discard heap.pop()
  63. doAssert heapProperty(heap)
  64. discard heap.pop()
  65. doAssert heapProperty(heap)
  66. heap.del(2)
  67. doAssert heapProperty(heap)
  68. # [2, 3, 5, 4, 42]
  69. discard heap.replace(12)
  70. doAssert heapProperty(heap)
  71. discard heap.replace(1)
  72. doAssert heapProperty(heap)
  73. discard heap.pushpop(2)
  74. doAssert heapProperty(heap)
  75. discard heap.pushpop(0)
  76. doAssert heapProperty(heap)
  77. static: main()
  78. main()