Skip to content

Commit

Permalink
infinity cycle fix
Browse files Browse the repository at this point in the history
  • Loading branch information
dageavtobusnick committed Jan 22, 2025
1 parent bc54b78 commit b745ad6
Showing 1 changed file with 33 additions and 19 deletions.
52 changes: 33 additions & 19 deletions code/__HELPERS/data_struct/priority_queue.dm
Original file line number Diff line number Diff line change
@@ -1,34 +1,48 @@
/priority_queue
var/list/heap = list()
var/list/priority_node/heap = list()

/priority_queue/proc/enqueue(value, priority)
heap += list(list(priority, value))
bubble_up(heap.len)
/priority_node
var/item
var/priority

/priority_queue/proc/dequeue()
if (heap.len == 0)
return null
/priority_node/New(item, priority)
. = ..()
src.item = item
src.priority = priority

var/list/top = heap[1]
heap[1] = heap[heap.len]
heap.Cut(heap.len, heap.len)
bubble_down(1)
/priority_queue/proc/enqueue(value, priority)
heap += list(new /priority_node(value, priority))
bubble_up(heap.len)

return top[2]
/priority_queue/proc/dequeue()
if (heap.len == 0)
return null

var/priority_node/top = heap[1]
var/bottom = heap[heap.len]
var/item = top.item
heap -= bottom
if(!heap.len)
qdel(top)
return item
heap[1] = bottom
bubble_down(1)
qdel(top)
return item

/priority_queue/proc/peek()
if (heap.len == 0)
return null
return heap[1][2]
if (heap.len == 0)
return null
return heap[1].item

/priority_queue/proc/is_empty()
return heap.len == 0
return heap.len == 0

/priority_queue/proc/bubble_up(index)
while(index > 1)
var/parent = round(index / 2)

if (heap[parent][1] < heap[index][1])
if (heap[parent].priority < heap[index].priority)
break

swap(index, parent)
Expand All @@ -39,10 +53,10 @@
while(index * 2 <= heap.len)
var/child = index * 2

if (child + 1 <= heap.len && heap[child + 1][1] < heap[child][1])
if (child + 1 <= heap.len && heap[child + 1].priority < heap[child].priority)
child++

if (heap[index][1] < heap[child][1])
if (heap[index].priority < heap[child].priority)
break

swap(index, child)
Expand Down

0 comments on commit b745ad6

Please sign in to comment.