File: queue.p

package info (click to toggle)
cloc 2.04-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 7,776 kB
  • sloc: perl: 29,368; cpp: 1,219; ansic: 334; asm: 267; makefile: 240; sh: 186; sql: 144; java: 136; ruby: 111; cs: 104; python: 84; pascal: 52; lisp: 50; cobol: 35; f90: 35; haskell: 35; objc: 25; php: 22; javascript: 15; fortran: 9; ml: 8; xml: 7; tcl: 2
file content (75 lines) | stat: -rw-r--r-- 2,004 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// https://github.com/compuphase/pawn/tree/main/examples/queue.p
/* Priority queue (for simple text strings) */
#include <string>

@start()
    {
    var msg[.text{40}, .priority]

    /* insert a few items (read from console input) */
    printf "Please insert a few messages and their priorities; " ...
           "end with an empty string\n"
    for ( ;; )
        {
        printf "Message:  "
        getstring msg.text, .pack = true
        if (strlen(msg.text) == 0)
            break
        printf "Priority: "
        msg.priority = getvalue()
        if (!insert(msg))
            {
            printf "Queue is full, cannot insert more items\n"
            break
            }
        }

    /* now print the messages extracted from the queue */
    printf "\nContents of the queue:\n"
    while (extract(msg))
        printf "[%d] %s\n", msg.priority, msg.text
    }

const queuesize = 10
var queue[queuesize][.text{40}, .priority]
var queueitems = 0

insert(const item[.text{40}, .priority])
    {
    /* check if the queue can hold one more message */
    if (queueitems == queuesize)
        return false            /* queue is full */

    /* find the position to insert it to */
    var pos = queueitems        /* start at the bottom */
    while (pos > 0 && item.priority > queue[pos-1].priority)
        --pos                   /* higher priority: move up a slot */

    /* make place for the item at the insertion spot */
    for (var i = queueitems; i > pos; --i)
        queue[i] = queue[i-1]

    /* add the message to the correct slot */
    queue[pos] = item
    queueitems++

    return true
    }

extract(item[.text{40}, .priority])
    {
    /* check whether the queue has one more message */
    if (queueitems == 0)
        return false
        /* queue is empty */

    /* copy the topmost item */
    item = queue[0]
    --queueitems

    /* move the queue one position up */
    for (var i = 0; i < queueitems; ++i)
        queue[i] = queue[i+1]

    return true
    }