theapqueue.nim 2.4 KB

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