TGC Codebase Backup



Using an array as a queue by IanM

15th Sep 2003 14:00
Summary

Simple readable example of using an array as a queue



Description

Simple readable example of using an array as a queue



Code
                                    ` This code was downloaded from The Game Creators
                                    ` It is reproduced here with full permission
                                    ` http://www.thegamecreators.com
                                    
                                    ` Demonstration of the queue commands
`
` ADD TO QUEUE       - Adds a new item to the end of the array and
`                       sets the current index to point to that item.
` REMOVE FROM QUEUE  - Removes the first item at the front of the
`                       array sets the current index to point to the
`                       new front item.
` I use ArrayName() to access the current item (eg to set the values
`                       in the item just added to the queue).
` I use ArrayName(0) to access the front of the queue (eg to read the
`                       values prior to removing from the queue)
`                       - see below for the reason.

` Several things to note here:
`   Adding to the queue automatically increases the size of the array.
`   Removing from the queue automatically decreases the size of the
`     array.
`   You cannot create an empty array (at the moment - Lee may include
`     it in Update 6) so the array needs to be cleared before you use
`     it.
`   No example of the 'array index to queue', because there is simply
`     no need for this command (in my opinion).
`     All it does is set the current index to the first item of the
`     array, and you can get that value yourself by accessing array(0).
`     Adding a new item to the queue resets the index to the last item
`     in the array, and continually switching back to get the next
`     value at the front of the queue is a pain.

dim a() as integer
empty array a()

print "Add 5 items to the queue"
for i=1 to 5
   n = rnd(1000)
   print "  Adding "; n; " to the queue"
   add to queue a()
   a() = n
next i

print
PrintQueue()
print
print "Pop 2 items from the queue"

for i=1 to 2
   print "  Removing "; a(0); " from the queue"
   remove from queue a()
next i

print
PrintQueue()
print

print "Add 5 more entries to the queue"
for i=0 to 4
   n = rnd(1000)
   print "  Adding "; n; " to the queue"

   add to queue a()
   a() = n
next i

print
PrintQueue()
print

print "Now remove items until the queue is empty"
while array index valid( a() )
   print "  Removing "; a(0); " from the queue"
   remove from queue a()
endwhile

print
PrintQueue()

wait key
end

function PrintQueue()
   if array count( a() ) >= 0
      print "The queue has "; array count( a() )+1; " items"
      for i=0 to array count( a() )
         print "  Item "; i; " = "; a(i)
      next i
   else
      print "The queue is empty"
   endif
endfunction