| 1 |
// https://github.com/compuphase/pawn/tree/main/examples/queue.p |
| 2 |
/* Priority queue (for simple text strings) */ |
| 3 |
#include <string> |
| 4 |
|
| 5 |
@start() |
| 6 |
{ |
| 7 |
var msg[.text{40}, .priority] |
| 8 |
|
| 9 |
/* insert a few items (read from console input) */ |
| 10 |
printf "Please insert a few messages and their priorities; " ... |
| 11 |
"end with an empty string\n" |
| 12 |
for ( ;; ) |
| 13 |
{ |
| 14 |
printf "Message: " |
| 15 |
getstring msg.text, .pack = true |
| 16 |
if (strlen(msg.text) == 0) |
| 17 |
break |
| 18 |
printf "Priority: " |
| 19 |
msg.priority = getvalue() |
| 20 |
if (!insert(msg)) |
| 21 |
{ |
| 22 |
printf "Queue is full, cannot insert more items\n" |
| 23 |
break |
| 24 |
} |
| 25 |
} |
| 26 |
|
| 27 |
/* now print the messages extracted from the queue */ |
| 28 |
printf "\nContents of the queue:\n" |
| 29 |
while (extract(msg)) |
| 30 |
printf "[%d] %s\n", msg.priority, msg.text |
| 31 |
} |
| 32 |
|
| 33 |
const queuesize = 10 |
| 34 |
var queue[queuesize][.text{40}, .priority] |
| 35 |
var queueitems = 0 |
| 36 |
|
| 37 |
insert(const item[.text{40}, .priority]) |
| 38 |
{ |
| 39 |
/* check if the queue can hold one more message */ |
| 40 |
if (queueitems == queuesize) |
| 41 |
return false /* queue is full */ |
| 42 |
|
| 43 |
/* find the position to insert it to */ |
| 44 |
var pos = queueitems /* start at the bottom */ |
| 45 |
while (pos > 0 && item.priority > queue[pos-1].priority) |
| 46 |
--pos /* higher priority: move up a slot */ |
| 47 |
|
| 48 |
/* make place for the item at the insertion spot */ |
| 49 |
for (var i = queueitems; i > pos; --i) |
| 50 |
queue[i] = queue[i-1] |
| 51 |
|
| 52 |
/* add the message to the correct slot */ |
| 53 |
queue[pos] = item |
| 54 |
queueitems++ |
| 55 |
|
| 56 |
return true |
| 57 |
} |
| 58 |
|
| 59 |
extract(item[.text{40}, .priority]) |
| 60 |
{ |
| 61 |
/* check whether the queue has one more message */ |
| 62 |
if (queueitems == 0) |
| 63 |
return false |
| 64 |
/* queue is empty */ |
| 65 |
|
| 66 |
/* copy the topmost item */ |
| 67 |
item = queue[0] |
| 68 |
--queueitems |
| 69 |
|
| 70 |
/* move the queue one position up */ |
| 71 |
for (var i = 0; i < queueitems; ++i) |
| 72 |
queue[i] = queue[i+1] |
| 73 |
|
| 74 |
return true |
| 75 |
} |