ttypenoval.nim 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. discard """
  2. errormsg: "type mismatch: got <typedesc[int]> but expected 'int'"
  3. file: "ttypenoval.nim"
  4. line: 38
  5. """
  6. # A min-heap.
  7. type
  8. TNode[T] = tuple[priority: int, data: T]
  9. TBinHeap[T] = object
  10. heap: seq[TNode[T]]
  11. last: int
  12. PBinHeap[T] = ref TBinHeap[T]
  13. proc newBinHeap*[T](heap: var PBinHeap[T], size: int) =
  14. new(heap)
  15. heap.last = 0
  16. newSeq(heap.heap, size)
  17. #newSeq(heap.seq, size)
  18. proc parent(elem: int): int {.inline.} =
  19. return (elem-1) div 2
  20. proc siftUp[T](heap: PBinHeap[T], elem: int) =
  21. var idx = elem
  22. while idx != 0:
  23. var p = parent(idx)
  24. if heap.heap[idx] < heap.heap[p]:
  25. swap(heap.heap[idx], heap.heap[p])
  26. idx = p
  27. else:
  28. break
  29. proc add*[T](heap: PBinHeap[T], priority: int, data: T) =
  30. var node: TNode[T]
  31. node.priority = int
  32. node.data = data
  33. heap.heap[heap.last] = node
  34. siftUp(heap, heap.last)
  35. inc(heap.last)
  36. proc print*[T](heap: PBinHeap[T]) =
  37. for i in countup(0, heap.last):
  38. echo($heap.heap[i])
  39. var
  40. heap: PBinHeap[int]
  41. newBinHeap(heap, 256)
  42. add(heap, 1, 100)
  43. print(heap)