Guest User

Untitled

a guest
Apr 25th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.38 KB | None | 0 0
  1. # BinaryHeap and PriorityQueue based on my Objective-C version
  2.  
  3. class JBBBinaryHeap
  4. def initialize(isMaxHeap = false)
  5. @mStorage = []
  6. @mCompareProc = (isMaxHeap) ? lambda { |x, y| x < y } : lambda { |x, y| x > y }
  7. end
  8.  
  9. def add(objectToAdd)
  10. @mStorage.push(nil)
  11. lastIndex = @mStorage.length - 1
  12. while (lastIndex > 0)
  13. parent = (lastIndex - 1) / 2
  14. parentNode = @mStorage[parent]
  15. break if (@mCompareProc.call(objectToAdd, parentNode))
  16. @mStorage[lastIndex] = parentNode
  17. lastIndex = parent
  18. end
  19. @mStorage[lastIndex] = objectToAdd
  20. end
  21.  
  22. def remove
  23. returnNode = @mStorage[0]
  24. lastNode = @mStorage.pop
  25. shiftDown(0, lastNode)
  26. return returnNode
  27. end
  28.  
  29. def min
  30. return @mStorage[0]
  31. end
  32.  
  33. def shiftDown(index, objectToShift)
  34. return if @mStorage.empty?
  35.  
  36. while (index < (@mStorage.size / 2))
  37. child = (2 * index) + 1
  38.  
  39. child += 1 if ((child < (@mStorage.size - 1)) and @mCompareProc.call(@mStorage[child], @mStorage[child + 1]))
  40.  
  41. break unless (@mCompareProc.call(objectToShift, @mStorage[child]))
  42.  
  43. @mStorage[index] = @mStorage[child]
  44. index = child
  45. end
  46. @mStorage[index] = objectToShift
  47. end
  48.  
  49. def size
  50. return @mStorage.size
  51. end
  52. alias length size
  53.  
  54. def empty?
  55. return @mStorage.empty?
  56. end
  57.  
  58. def to_s
  59. return @mStorage.to_s
  60. end
  61. end
  62.  
  63. class JBBPQueue
  64. def initialize(isMaxQueue = false)
  65. @mObjs = JBBBinaryHeap.new(isMaxQueue)
  66. @mObjsArray = []
  67. @mHeapified = false
  68. end
  69.  
  70. def buildHeap
  71. return if (@mHeapified)
  72.  
  73. @mObjsArray.each { |item| @mObjs.add(item) }
  74. @mObjsArray.clear
  75. @mHeapified = true
  76. end
  77.  
  78. def push(objectToAdd)
  79. if (@mHeapified)
  80. @mObjs.add(objectToAdd)
  81. else
  82. @mObjsArray.push(objectToAdd)
  83. end
  84. end
  85.  
  86. def pushObjects(objectsToAdd = [])
  87. @mHeapified = false
  88.  
  89. @mObjsArray += objectsToAdd
  90. end
  91.  
  92. def pop
  93. return nil if empty?
  94.  
  95. buildHeap
  96.  
  97. return @mObjs.remove
  98. end
  99.  
  100. def size
  101. return @mObjs.size + @mObjsArray.size
  102. end
  103.  
  104. def empty?
  105. return (size == 0)
  106. end
  107.  
  108. def to_s
  109. buildHeap
  110.  
  111. return @mObjs.to_s
  112. end
  113. end
Add Comment
Please, Sign In to add comment