/* * File name: simpsim.cpp * Author: Xiannong Meng * Date: February 15, 1997 * Course: CS2330 * Assignment: classroom demonstration * Problem statement: * This is a traffic simulation program using random numbers. * */ #include #include // rand and srand are in stdlib.h // define event type enum Event {Idle, ArrvN, ArrvS, ArrvE, ArrvW}; // user defined constants and functions // they can be in a separate header file const int NUMEVNTYPE = 5; // five different types of events void Simulation(int); // main simulation loop Event EventGen(void); // event generator void FromNorth(void); // five event handlers void FromSouth(void); void FromEast(void); void FromWest(void); void Wait(void); void main(void) { int time; // simulation time limit int seed; // random seed cout << " type a random seed : "; cin >> seed; srand(seed); cout << " type a time limit : "; cin >> time; Simulation(time); } // Name: Simulation // Intent: loop until the time expires, generate // and process events in between // Pre-condition: total simulation time specified // Post-contidion: simulation finished void Simulation(int timeLimit) { int currentTime = 0; Event event; while (currentTime < timeLimit) { event = EventGen(); switch (event) { case Idle : Wait(); break; case ArrvN : FromNorth(); break; case ArrvS : FromSouth(); break; case ArrvE : FromEast(); break; case ArrvW : FromWest(); break; default: cout << " error in event type " << endl; } currentTime += 1; } } // Name: EventGen // Inteng: event generator // Pre-condition: none // Post-condition: generates one event Event EventGen() { return (Event)(rand() % NUMEVNTYPE); } // Name: FromNorth // Intent: representing one vehicle from north direction // Pre-condition: simulation started // Post-condition: event processed void FromNorth() { cout << " one vehicle from north \n"; } // Name: FromSouth // Intent: representing one vehicle from south direction // Pre-condition: simulation started // Post-condition: event processed void FromSouth() { cout << " one vehicle from south \n"; } // Name: FromEast // Intent: representing one vehicle from east direction // Pre-condition: simulation started // Post-condition: event processed void FromEast() { cout << " one vehicle from east \n"; } // Name: FromWest // Intent: representing one vehicle from west direction // Pre-condition: simulation started // Post-condition: event processed void FromWest() { cout << " one vehicle from west \n"; } // Name: Wait // Intent: traffic is busy, newly arrived vehicle has to wait // Pre-condition: simulation started, one vehicle is at // intersection // Post-condition: vehicle waits void Wait() { cout << " traffic busy, wait ... \n"; }