Priority queue: Difference between revisions
m
→Using a stack with pointers to Groups as elements
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
ObjectCount()
zz=stack
while not empty
InsertPQ(
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(
Header()
while n1
Print @Peek$(stackitem(n1))
end while
ObjectCount()
Header()
while not @isEmpty(
Print @Pop(
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,
local m=
while t<=
t1=m
m=(
if m=0 then m=t1 : exit
If @comp(stackitem(m),n) then t=m+1: continue
m=
end while
if m>1 then shiftback m
}
end sub
function comp(a as *obj,
=a=>x
end function
function Peek$(a as
=
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}
end function
}
|