TGC Codebase Backup



Using an array as a stack by IanM

15th Sep 2003 14:01
Summary

Simple readable example of using an array as a stack



Description

Simple readable example of using an array as a stack



Code
                                    ` This code was downloaded from The Game Creators
                                    ` It is reproduced here with full permission
                                    ` http://www.thegamecreators.com
                                    
                                    ` Demonstration of the stack commands
`
` ADD TO stack       - Adds a new item to the end of the array and
`                       sets the current index to point to that item.
` REMOVE FROM stack  - 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 stack, and to
`                       read the value at the top of the stack).

` Several things to note here:
`   Adding to the stack automatically increases the size of the array.
`   Removing from the stack 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 stack', because the current item
`     is always pointing to the top of the stack either when adding
`     or removing. This command may be required when switching between
`     using and array/queue/list as a stack.

dim a() as integer
empty array a()

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

print
PrintStack()
print
print "Pop 2 items from the stack"

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

print
PrintStack()
print

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

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

print
PrintStack()
print

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

print
PrintStack()

wait key
end

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