musifter

AoC Smalltalk Heap.st module

Dec 8th, 2025 (edited)
25
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Smalltalk 1.86 KB | Source Code | 0 0
  1. " Heap class to implement priority queue "
  2. Object subclass: Heap [
  3.     | arr end |
  4.     Heap class >> new       [ ^super new init: 20000 ]
  5.     Heap class >> new: size [ ^super new init: size  ]
  6.  
  7.     init: size [
  8.         arr := Array new: size.
  9.         end := 0.
  10.         ^self
  11.     ]
  12.  
  13.     isEmpty  [ ^(end  = 0) ]
  14.     notEmpty [ ^(end ~= 0) ]
  15.  
  16.     heapify: idx [
  17.         | left right smallest |
  18.         left  := 2 * idx.
  19.         right := 2 * idx + 1.
  20.  
  21.         smallest := idx.
  22.  
  23.         ((left <= end) and: [(arr at: idx) > (arr at: left)]) ifTrue: [
  24.             smallest := left
  25.         ].
  26.  
  27.         ((right <= end) and: [(arr at: smallest) > (arr at: right)]) ifTrue: [
  28.             smallest := right
  29.         ].
  30.  
  31.         (smallest ~= idx) ifTrue: [
  32.             arr swap: idx with: smallest.
  33.             self heapify: smallest.
  34.         ]
  35.     ]
  36.  
  37.     insert: item [
  38.         | i parent |
  39.         end := end + 1.
  40.         (end > arr size) ifTrue: [
  41.             stderr nextPutAll: ('Heap size (%1) exceeded!' % {arr size}); nl.
  42.             Error signal.
  43.         ].
  44.  
  45.         arr at: end put: item.
  46.  
  47.         i := end.
  48.         [(i ~= 1) and: [(arr at: (parent := i // 2)) > (arr at: i)]] whileTrue: [
  49.             arr swap: i with: parent.
  50.             i := parent.
  51.         ].
  52.         ^item
  53.     ]
  54.  
  55.     next [
  56.         | top |
  57.         (end = 0) ifTrue: [ ^nil ].
  58.  
  59.         top := arr first.
  60.         end := end - 1.
  61.  
  62.         (end > 0) ifTrue: [
  63.             arr at: 1 put: (arr at: end + 1).
  64.             self heapify: 1.
  65.         ].
  66.         ^top
  67.     ]
  68.  
  69.     peek [
  70.         ^(end = 0) ifTrue: [nil] ifFalse: [arr first]
  71.     ]
  72.  
  73.     printOn: aStream [
  74.         (end = 0) ifTrue: [
  75.             aStream nextPutAll: 'Heap (empty)'.
  76.         ] ifFalse: [
  77.             aStream nextPutAll: 'Heap (size: %1, top: %2)' % {end. arr first}.
  78.         ]
  79.     ]
  80. ]
  81.  
Advertisement
Add Comment
Please, Sign In to add comment