Priority queue: Difference between revisions

Content added Content deleted
Line 4,591: Line 4,591:


<syntaxhighlight lang="m2000 interpreter">
<syntaxhighlight lang="m2000 interpreter">
// class definitions are global
// if there aren't defintions in a class
global countmany=0&
class obj {
x, s$
property toString$ {
value (sp=8) {
link parent x, s$ to x, s$
value$=format$("{0::-5}"+string$(" ", sp)+"{1:20}", x, s$)
}
}
remove {
countmany--
}
class:
module obj (.x, .s$) {countmany++}
}
Module PriorityQueueForGroups {
Module PriorityQueueForGroups {
class obj {
x, s$
class:
module obj (.x, .s$) {}
}
Flush ' empty current stack
Flush ' empty current stack
Data obj(3, "Clear drains"), obj(4 ,"Feed cat"), obj( 5 , "Make tea"), obj( 1 ,"Solve RC tasks"), obj( 2 , "Tax return")
Data obj(3, "Clear drains"), obj(4 ,"Feed cat"), obj( 5 , "Make tea")
Data obj( 1 ,"Solve RC tasks"), obj( 2 , "Tax return")
ObjectCount()
b=stack
b=stack
comp=lambda (a, b) ->{
while not empty
=a.x<b.x
InsertPQ(b) // top of stack is b then objects follow
}
end while
module InsertPQ (a, n, &comp) {
ObjectCount()
Print "Using Peek to Examine Priority Queue"
if len(a)=0 then stack a {data n} : exit
n1=each(b)
if comp(n, stackitem(a)) then stack a {push n} : exit
stack a {
Header()
while n1
Print @Peek$(n1)
end while
ObjectCount()
Header()
while not @isEmpty(b)
Print @Pop(b)=>tostring$
end while
ObjectCount()
// here are the subs/simple functions
// these are static parts of module
sub Header()
Print " Priority Task"
Print "========== ================"
end sub
sub ObjectCount()
Print "There are ";countmany;" objects of type obj"
end sub
sub InsertPQ(a, n)
Print "Insert:";n.tostring$(1)
if len(a)=0 then stack a {data n} : exit sub
if @comp(n, stackitem(a)) then stack a {push n} : exit sub
stack a {
push n
push n
t=2: b=len(a)
local t=2, b=len(a)
m=b
local m=b
while t<=b {
while t<=b
t1=m
t1=m
m=(b+t) div 2
m=(b+t) div 2
if m=0 then m=t1 : exit
if m=0 then m=t1 : exit
If comp(stackitem(m),n) then t=m+1: continue
If @comp(stackitem(m),n) then t=m+1: continue
b=m-1
b=m-1
m=b
m=b
}
end while
if m>1 then shiftback m
if m>1 then shiftback m
}
}
}
end sub
b=stack
function comp(a, b)
While not empty {
=a.x<b.x
end function
InsertPQ b, Group, &comp ' Group pop a group from current stack
function Peek$(a as stack)
}
n1=each(b)
=stackitem(a)=>toString$
while n1 {
countmany++
m=stackitem(n1)
end function
function IsEmpty(a)
Print m.x, m.s$
}
=len(a)=0
end function
Function Peek$(a) {m=stackitem(a) : =m.s$}
Print Peek$(b)
Function Pop(a)
// Group make a copy
Function Pop$(a) {
stack a {=Group:countmany++}
stack a {
end function
m=stackitem()
=m.s$
drop
}
}
Function IsEmpty(a) {
=len(a)=0
}
While not isEmpty(b) {
Print Pop$(b)
}
}
}
PriorityQueueForGroups
PriorityQueueForGroups