theapqueue.nim 2.3 KB

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