Priority queue: Difference between revisions

m
Line 4,676:
</syntaxhighlight>
 
===Using a stack with pointers to Groups as elements (with Merge Function)===
Now we use pointer to group, and use of Subs and simple Functions (called using @ prefix). Also we have a global countmany (is a long type, see 0&) to check how many objects exist. We have use "as *obj" to declare a parameter to stay as pointer and to check the type (here is obj). The remove method of object called when object has to be removed. The constructor module obj called once and not exist in the final object obj (it is a part under Class: label, and this part define things for construction time only). Property toString$ is a group which return value (a string value), and we can use it with or without parameter. Because it is a group, we have to link parent properties/functions (but not modules) to get access.
 
Added Merge function.
 
<syntaxhighlight lang="m2000 interpreter">
Line 4,705 ⟶ 4,706:
Flush ' empty current stack
Data g(3, "Clear drains"),g(4 ,"Feed cat"), g( 5 , "Make tea")
Data g( 1 ,"Solve RC tasks"), g( 2 , "Tax return")
ObjectCount()
bpq=stack
zz=stack
while not empty
InsertPQ(bpq) // top of stack is bpq then objects follow
end while
Pen 15 {
data g(2 , "Tax return"), g(1 ,"Solve RC tasks#2")
while not empty: InsertPq(zz): End While
n1=each(zz)
Header()
while n1
Print @Peek$(stackitem(n1))
end while
}
MergePq(pq, zz)
InsertPq(pq, g(1 ,"Solve RC tasks#3"))
ObjectCount()
Print "Using Peek to Examine Priority Queue"
n1=each(bpq,-1, 1)
Header()
while n1
Print @Peek$(stackitem(n1))
end while
ObjectCount()
Header()
while not @isEmpty(bpq)
Print @Pop(bpq)=>tostring$
end while
ObjectCount()
Line 4,732 ⟶ 4,745:
sub ObjectCount()
Print "There are ";countmany;" objects of type obj"
end sub
sub MergePq(a, pq)
local n1=each(pq), z=pointer()
while n1
z->(stackitem(n1))
InsertPQ(a, z)
end while
end sub
sub InsertPQ(a, n as *obj)
Line 4,739 ⟶ 4,759:
stack a {
push n
local t=2, bpq=len(a), t1=0
local m=bpq
while t<=bpq
t1=m
m=(bpq+t) div 2
if m=0 then m=t1 : exit
If @comp(stackitem(m),n) then t=m+1: continue
bpq=m-1
m=bpq
end while
if m>1 then shiftback m
}
end sub
function comp(a as *obj, bpq as *obj)
=a=>x<b>pq=>x
end function
function Peek$(a as stack*obj)
=stackitem(a)=>toString$
end function
function IsEmpty(a)
Line 4,763 ⟶ 4,783:
function Pop(a)
// Group make a copy (but here is a pointer of group)
stack a {=Group}shift stack.size
=Group}
end function
}
404

edits