Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

DMV Line Queue Simulator

Posted on 2005-04-12
4
Medium Priority
?
896 Views
Last Modified: 2010-05-18
>> ok...this code compiles and run,...would you please check if the code below is what is being asked,...and if not...would you please help in the modification.

*************************************Code***********************************************

# Makefile:
#           It uses the C++ Compiler with all warnings and
#           debugging enabled. A single executable will
#           be produced.
# ---------------------------------------------------------------
CPP = g++
CFLAGS = -L/usr/lib/cmplrs/cxx -DPOSIX_4D9
DFLAGS = -g
LD = g++
LLIBS = -lm
#
# Linker Flags:
# set "-lm" if we need to use the "math" functions
CLIBS= -lm
RM = rm -f
# ----------------------------------------------------------------
# Explanation of macros:
#     $< is any dependent file which is out of date
#     $* is the target's basename (without extension)
#     $@ is the target's fullname
#
# In general ".cpp" (unlike ".c") is not automatically recognized as a
# reserved suffix, so we should inform "make" in case we use this later:
.SUFFIXES:      .cpp .o
#
# implicit rule for compilation only:
.cpp.o:
      ${CPP} -c ${DFLAGS} ${CFLAGS} $<

OFILES=            main.o queue.o server.o citizen.o

HFILES=            queue.h server.h citizen.h  

# dependencies
#
default:      all
all:              main      
#
main:           $(OFILES)
            ${LD} ${CFLAGS} ${LLIBS} $(OFILES) -o $@

main.o:            main.cpp

queue.o:      queue.cpp queue.h

server.o:      server.cpp server.h

citizen.o:      citizen.cpp citizen.h

#
clean:
      ${RM} *.o
      ${RM} core
#
veryclean:      clean
      ${RM}  main  


***************************************

#ifndef QUEUE_H
#define QUEUE_H

#include <iostream>

using namespace std;

const int MAXSIZE = 100;         //Maximum size of the queue.
      
class Queue
{
friend ostream& operator<< (ostream&, Queue&);
        
public:
   Queue ();
            
   void push           (int n);      //Add person to the queue
   void pop            ();           //Remove person from beginning of queue
   int  getFirstInLine ();           //Get a copy of the first person in line
   bool isEmpty        ();
   
private:
   int size;                   //Queue length
   int line [MAXSIZE];
};
        
#endif

********************************

#include <iomanip>

#include "queue.h"
      
const int WIDTH = 5;  //Print field size
      
Queue::Queue ()
{
    size = 0;
}
        
void Queue::push (int n)
{
   if (size < MAXSIZE)
   {
        line [size] = n;
        size++;
   }
}
        
void Queue::pop ()
{  
    if (size > 0)
    {    
    //Remove the person at the beginning by moving
    //  everyone else forward one place.
      
       for (int n = 0; n < size - 1; n++)
          line [n] = line [n + 1];
             
       size--;
    }
}

int Queue::getFirstInLine ()
{
    //Return a copy of the first person in line.
   
    int temp = 0;
   
    if (size > 0)
       temp = line [0];
       
    return temp;
}

bool Queue::isEmpty ()
{
   return size == 0;
}
              
ostream& operator<< (ostream& out, Queue& Q)
{
    for (int n = 0; n < Q.size; n++)
        out << setw (WIDTH) << Q.line [n];
         
    return out;
}      

*****************************************



#include "queue.h"

#ifndef SERVER_H
#define SERVER_H
      
#include <iostream>
      
using namespace std;
      
//class invariantfor the service class:

//A server object represents a station where a person receives
//  a service (banking, haircut, etc., etc.).

//A server object contains:
//  1)  a person number, that represents the person getting the service.
//  2)  a timer, that records how long the person has been getting the servic.
//  3)  a service time, that is the limit of the time a person gets service.
//         When the timer reaches the service time, then the person is removed.

class server
{
friend ostream& operator<< (ostream&, server&);
       
public:
    server (int);                 //The n is the time to service a person.
         
    bool isAvailable  ();         //True if noone is present, otherwise false
   
    void StartService (int n);    //n is the person to service
   
    void Update       ();         //Ups the timer, kicks the person
                                  //  out when the time is up.
       
private:
    int person;
    int timer;
    int serviceTime;
};

#endif

**********************************************


#include <iomanip>
     
#include "server.h"
     
const int WIDTH  = 5;           //Width of print fields
const int NOBODY = 0;

server::server (int time)      
{
//Initialize the person to empty, the time to 0, and set the length of
//  the service time.

    person      = NOBODY;
    timer       = 0;
    serviceTime = time;
}
       
bool server::isAvailable  ()
{
    bool returnVal = false;
   
    if (person == NOBODY)
       returnVal = true;
     
    return returnVal;
}
     
void server::StartService (int n)
{
//n is the number of the person to be serviced.  Since service is
//  starting, set the timer to 0.

    person = n;
    timer  = 0;
}
       
void server::Update ()
{
//Add a minute to the timer.  If the service time is reached, then
//  the person being serviced is done, so remove him/her, and reset
//  the time to 0.

    timer++;
         
    if (timer == serviceTime)  
    {
        person = NOBODY;
        timer  = 0;
    }
}
       
ostream& operator<< (ostream& out, server& service)
{
    if (!service.isAvailable ())
        out << setw (WIDTH) << service.person;
       
    else
        cout << setw (WIDTH) << "   ";
         
    return out;
}

**********************************************


#include "server.h"

#ifndef CITIZEN_H
#define CITIZEN_H

//class invariant for the arrivalGenerator class:

//An arrivalGenerator object generates the number of the next person arriving
//  for service, if there is one.  Whether or not a person arrives is
//  determined at random according to a set probability.

//The arrivalGenerator object contains:
//  1)  The probability that is used to determine if an arrival occurs.
//  2)  The number of the next arrival, as an identifier for that person.
 
class Citizen
{
public:
    Citizen (int, double);  //The int is a seed for the random
                            //  number generation.
                            //The double is the probability to
                            //  be usedfor generating random    
                            //  numbers.
       
    bool isArrival ();      //True if an arrival occurs.
   
    int  getArrival ();     //The number of the last person arriving.
           
private:
    double probability;
    int    nextCustomer;
};
     
#endif

****************************************


#include "citizen.h"

#include <cstdlib>       //For srand and rand

Citizen::Citizen(int    s,   //srand seed
                                    double P)   //Probability of arrival
{
   srand (s);             //seed the random sequence
   
   probability   = P;
   nextCustomer  = -1;
}

bool Citizen::isArrival ()
{
   bool returnVal = false;
       
   double event = rand () % 100 + 1;   //Get a random number betw
                                       //  1 and 100
       
   if (event / 100.0 <= probability)   //Determine if an arrival
                                       //  occurred
   {      
       returnVal = true;
       nextCustomer++;
   }
         
   return returnVal;
}

int Citizen::getArrival ()
{
   return nextCustomer;
}

***********************************


#include <iostream>
#include <iomanip>
      
#include "queue.h"
#include "server.h"
#include "citizen.h"
      
const int   SERVICETIME   = 3;
const int   SEED          = 6;
const float PROBABILITY   = .333;
const int   WIDTH         = 6;
const int   MAXTIME       = 50;
      
int main ()
{
                 
      server teller (SERVICETIME);      //Set up the teller with the
                                        //  given service time.
        
      Queue line;                  
      
      Citizen arrivalMachine (SEED, PROBABILITY);
               
      cout << "Minute    " << "Serving    "       //Table headings
           << "Queue"      << endl;
              
      //Run throught the minutes of the simulation
      
      for (int minute = 0; minute <= MAXTIME; minute++)
      {
         //Teller advances its timer, removes customer if
         //   service is finished.
        
         teller.Update ();
                      
         //Generate an arrival (or not).  If there is an arrival put the
         //   person in line.
            
         if (arrivalMachine.isArrival ())          
             line.push (arrivalMachine.getArrival ());
        
         //If the teller is open, give first person in line to the
         //   teller for service, and remove the person from the line.
        
         if (teller.isAvailable ())  
         {
           teller.StartService (line.getFirstInLine ());
                   
           line.pop ();
         }
          
         //Display the current state of the teller and the line.
        
         cout << setw (WIDTH) << minute   << " > "
              << teller       << "     "  << line << endl;
      }
            
      return 0;
}         

**************************************************

output:

$ main
Minute    Serving    Queue
     0 >
     1 >     1
     2 >     1
     3 >     1
     4 >
     5 >
     6 >
     7 >
     8 >
     9 >
    10 >     2
    11 >     2
    12 >     2         3
    13 >     3
    14 >     3
    15 >     3
    16 >
    17 >     4
    18 >     4         5
    19 >     4         5    6
    20 >     5         6
    21 >     5         6
    22 >     5         6
    23 >     6
    24 >     6         7
    25 >     6         7    8
    26 >     7         8    9
    27 >     7         8    9
    28 >     7         8    9
    29 >     8         9   10
    30 >     8         9   10   11
    31 >     8         9   10   11
    32 >     9        10   11
    33 >     9        10   11
    34 >     9        10   11
    35 >    10        11
    36 >    10        11
    37 >    10        11   12
    38 >    11        12
    39 >    11        12
    40 >    11        12   13
    41 >    12        13   14
    42 >    12        13   14
    43 >    12        13   14   15
    44 >    13        14   15
    45 >    13        14   15   16
    46 >    13        14   15   16   17
    47 >    14        15   16   17   18
    48 >    14        15   16   17   18
    49 >    14        15   16   17   18
    50 >    15        16   17   18
edelossa@helios  test $ $

>> Is this code close and exact to what is being asked for below?

****************************************

Write a program that simulates a line at the Department of Motor Vehicles (DMV). The line is a queue object.  Citizens (i.e., citizen objects) arrive in random regular intervals of 1 – 10 minutes. Also, each citizen is served in random integer intervals of 1 – 10 minutes. Obviously, the rates need to be balanced. If the average arrival rate is larger than the average service rate, the queue will grow infinitely. Even with “balanced” rates, randomness can still cause long lines. Run the DMV simulation for an 8-hour day (480 minutes) using the following algorithm:

 

Choose a random integer between 1 and 10 to determine the minute at which the first citizen arrives.
At the first citizen’s arrival time:
Determine the citizen’s service time (random integer from 1 to 10);
Begin servicing the citizen;
Schedule arrival time of the next citizen (random integer 1 to 10 added to the current time).
For each minute of the day:
If the next citizen arrives,
                                                              i.      Announce the arrival of citizen N;

                                                            ii.      Enqueue the citizen;

                                                          iii.      Schedule the arrival time of the next citizen;

If service was completed for the last citizen,
                                                              i.      Announce service complete for citizen X;

                                                            ii.      Dequeue the next citizen to be serviced;

                                                          iii.      Determine the citizen’s service completion time (random integer from 1 to 10 added to the current time).

Now run your simulation for 480 minutes and answer each of the following questions:

>> Please advise.  Del
0
Comment
Question by:edelossantos
  • 2
  • 2
4 Comments
 
LVL 39

Assisted Solution

by:itsmeandnobodyelse
itsmeandnobodyelse earned 2000 total points
ID: 13765333
>>>> Is this code close and exact to what is being asked for below?

Yes and No.

Yes, cause it would need not much changes to meet the requirements.

No, as you are too close to the Runway sample and don't consider that the requirements are different here. So, you shouldn't work with probabilities but with relative schedule times randomly between 1 and 10. Also the service time should be determined randomly (now == 3).

I already started to solve the issues but will not finish before tomorrow.

Regards, Alex
0
 

Author Comment

by:edelossantos
ID: 13765358
Thank you Alex,...I will keep this open for tomorrow.  Del
0
 
LVL 39

Accepted Solution

by:
itsmeandnobodyelse earned 2000 total points
ID: 13770946
I put all sources (headers + cpp) to one cpp and commented header includes. I hope you don't have problems to separate it to the original files.

Regards, Alex

#ifndef QUEUE_H
#define QUEUE_H

#include <iostream>
using namespace std;

const int MAXSIZE        = 100;         //Maximum size of the queue.
const int MAXIDLE        = 10;          //Maximum size to wait for next arrival
const int MAXSERVICETIME = 10;          //Maximum size for service time
     
class Queue
{
friend ostream& operator<< (ostream&, Queue&);
       
public:
   Queue ();
           
   void push           (int n);      //Add schedule time to the queue
   void pop            ();           //Remove time from beginning of queue
   int  getFirst       ();           //Get a copy of the first time in line
   bool isEmpty        ();
   int  getAt          (int i);      //Get a copy of the entry at position i
   
private:
   int size;                   //Queue length

   int line [MAXSIZE];      
};
       
#endif

#include <iostream>
#include <iomanip>

// #include "queue.h"
using namespace std;
     
const int WIDTH = 5;  //Print field size
     
Queue::Queue ()
{
    size = 0;
}
       
void Queue::push (int n)
{
   if (size < MAXSIZE)
   {
        line [size] = n;
        size++;
   }
}
       
void Queue::pop ()
{  
    if (size > 0)
    {    
        //Remove the person at the beginning by moving
        //  everyone else forward one place.
       
        for (int n = 0; n < size - 1; n++)
            line [n] = line [n + 1];
       
        size--;
    }
}

int Queue::getFirst ()
{
    //Return a copy of the first person in line.
   
    int temp = 0;
   
    if (size > 0)
       temp = line [0];
       
    return temp;
}

int Queue::getAt (int idx)
{
    //Return a copy of the first person in line.
   
    int temp = 0;
   
    if (idx >= 0 && idx < size)
       temp = line [idx];
       
    return temp;
}

bool Queue::isEmpty ()
{
   return size == 0;
}
             
ostream& operator<< (ostream& out, Queue& Q)
{
    for (int n = 0; n < Q.size; n++)
        out << setw (WIDTH) << Q.line [n];
         
    return out;
}      




// #include "queue.h"

#ifndef SERVER_H
#define SERVER_H
     
#include <iostream>
     
using namespace std;
     
//class invariantfor the service class:

//A Server object represents a station where a person receives
//  a service (banking, haircut, etc., etc.).

//A Server object contains:
//  1)  a person number, that represents the person getting the service.
//  2)  a timer, that records how long the person has been getting the servic.
//  3)  a service time, that is the limit of the time a person gets service.
//         When the timer reaches the service time, then the person is removed.

class Server
{
friend ostream& operator<< (ostream&, Server&);
       
public:
    Server ();                    //
         
    bool isAvailable  ();         //True if noone is present, otherwise false
   
    void StartService (int n, int schedule);    //n is the person to service
   
    void Update       (int now);        //Ups the timer, kicks the person
                                        //  out when the time is up.
     
    int getServiceTime();

    int getPerson();

       
private:
    int person;
    int serviceTime;
};

#endif



#include <iomanip>
using namespace std;
     
// #include "Server.h"
     
const int NOBODY = -1;    

Server::Server ()      
{
//Initialize the person to empty, the service time to 0
    person      = NOBODY;
    serviceTime = 0;
}
       
bool Server::isAvailable  ()
{
    return (person == NOBODY);
}
     
void Server::Update(int now)
{
    if (now >= serviceTime)
    {
        person = NOBODY;
        serviceTime = 0;
    }
}

void Server::StartService (int n, int s)
{
//n is the number of the person to be serviced.  s the service time

    person = n;
    serviceTime = s;
}
       
       
int Server::getServiceTime()
{
    return (rand()%MAXSERVICETIME) + 1;
}

int Server::getPerson()
{
    return person;
}

ostream& operator<< (ostream& out, Server& service)
{
    if (!service.isAvailable ())
        out << setw (WIDTH) << service.person;
    else
        cout << setw (WIDTH) << "   ";
         
    return out;
}



// #include "Server.h"

#ifndef CITIZEN_H
#define CITIZEN_H

//class invariant for the arrivalGenerator class:

//An arrivalGenerator object generates the number of the next person arriving
//  for service, if there is one.  Whether or not a person arrives is
//  determined at random according to a set probability.

//The arrivalGenerator object contains:
//  1)  The probability that is used to determine if an arrival occurs.
//  2)  The number of the next arrival, as an identifier for that person.
 
class Citizen
{
public:
    //Make it static as we don't need an instance of Citizen
    static int arrival();

           
private:
};
     
#endif



// #include "citizen.h"

int Citizen::arrival()
{
    return (rand()%MAXIDLE)+1;
}


#include <iostream>
#include <iomanip>
using namespace std;

#include <time.h>    
// #include "queue.h"
// #include "server.h"
// #include "citizen.h"
     
const int    OFFSET        = 6;
const int    MAXTIME       = 50;
     
int main ()
{
    // init randomizer
    srand(time(NULL));

    Server teller;
    Queue  line;

    // announce the first arrival
    int nextArrival = Citizen::arrival();
    // push it to queue
    line.push(nextArrival);
    // next schedule
    int schedule;
    // We don't ned a Citizen object but only an ID (for output)
    int citizen = 0;

    // loop from 1 to MAXTIME
    for (int minute = 1; minute <= MAXTIME; minute++)
    {
        // repeat header all 25 lines
        if (minute%25 == 1)
        {
            cout << endl << "Minute    " << "Serving    "       //Table headings
                         << "Queue"      << endl;
        }
        // update server status if service time elapsed
        teller.Update(minute);
       
        // get next announced time
        schedule = line.getFirst();

        // if queue isn't empty and one or more people are waiting ...
        if (schedule > 0 && schedule <= minute)
        {
            // check if service desk is free
            if (teller.isAvailable())
            {
                // remove first from queue ...
                line.pop();
                // ... increase ID, calulate schedule time and start service
                teller.StartService(++citizen, teller.getServiceTime() + minute);
            }
            // announce a new arrival if last arrival matches current time
            if (nextArrival == minute)
            {
                // add a new announcement to queue
                nextArrival += Citizen::arrival();
                line.push(nextArrival);
            }
        }
        //Display the current state of the teller and the line.
       
        cout << setw (OFFSET) << minute   << " > "
             << teller       << "     ";
       
        int idx = 0;
        int next;
        int current = teller.getPerson();

        // we cannot use operator<<(..., Queue ) cause
        // the queue contains waiting citizen (schedule - minute <= 0)
        // and announcements (schedule > minute)
        if (current != NOBODY)
        {
            // print only waiting citizens where schedule time (next)
            // less or equal to current time
            while ((next = line.getAt(idx++)) > 0 && next <= minute)
                cout << setw(4) << ++current << "(" << setw(2) << minute-next << ")  ";
        }
        cout << endl;

    }
     return 0;
}        
0
 

Author Comment

by:edelossantos
ID: 13775009
A billion and one thank yous' Alex.  I wish I could give you more points.  Del
0

Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

C++ Properties One feature missing from standard C++ that you will find in many other Object Oriented Programming languages is something called a Property (http://www.experts-exchange.com/Programming/Languages/CPP/A_3912-Object-Properties-in-C.ht…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.
Suggested Courses

810 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question