"Data Structure" 3, Simulation Bank window queuing system--c++

Source: Internet
Author: User
Tags rand

Here we simulate the implementation of the Bank queuing system:


Suppose a bank has 4 windows to host clients. Because each window can only receive a customer at a certain time, in a large number of customers need to queue, for just enter the bank's customers, if a window is idle,
You can go to the front of the business, if all the windows are not idle in the fewest number of Windows.
It is now required to simulate a customer queuing situation for 4 windows within a certain time period of the bank. Here the customer arrives at the moment and the time to transact the business is random.



First of all, we have a bank event, we have to have a class that represents the Event object

/** function: This implementation is the data unit node of our event * file: event.h* time: July 8, 2015 20:55:32*cutter_point*/#ifndef event_h#define event_hclass event{ The int occurtime;//event occurs at the moment of the int ntype;//event type, 0 for the arrival event, and 1 to 4 for the departure event of four Windows Public:event ()//initialization, and we first treat the event and event type as 0{this- >occurtime = 0;this->ntype = 0;} Event (int occur, int type) {this->occurtime = Occur;this->ntype = type;} Override = operator, overload of operator/*event& operator= (const event& event) {if (event = = NULL) {}}*///set and get method void Setoccurtime (int Occurtime) {this->occurtime = Occurtime;} int Getoccurtime () {return this->occurtime;} void Setntype (int type) {this->ntype = type;} int Getntype () {return this->ntype;}}; #endif

Then we use a linked list to store our event chain.

/** function: This implementation is the function of the list * file: linklist.h* time: July 7, 2015 20:33:18, July 8, 2015 20:01:31*cutter_point*/#ifndef linklist_h#define Linklist_h#include "Event.h" #include a node of the <stdio.h>using namespace std;//list class node{event Event;//Create our Data meta object that contains an event occurrence time and an event type node* Next;public:node () {this->next = nullptr;} Node (Event e) {this->event = e; this->next = nullptr;} Set and Get methods void SetEvent (Event e) {this->event = e;} Event getEvent () {return this->event;} void Setnext (node* n) {this->next = n;} node* GetNext () {return this->next;}};/ /Our list class linklist{node* head;//head pointer node* gettail ();//Get tail pointer public:linklist () {this->head = new Node ();} void Insert (Event e);//Add an element to the end of the list node* pop (); Delete the last node bool Listempty ();//Determine whether the empty list node* gethead ();//Get the first pointer}; #endif

Realize:

/** function: This is the function of the linked list * file: linklist.cpp* time: July 7, 2015 20:33:18, July 8, 2015 20:01:31, July 9, 2015 20:42:11*cutter_point*/# Include "LinkList.h" #include <iostream>using namespace std;/************************************************ node****************************************************************************//********************** linklist********************************************************************** void Insert (event e);//Add an element to the end of the list void Linklist::insert (event e) {//Insert an element, first we determine whether the linked list contains an element bool A;if (A = this- >listempty ())//True is true this->head = new Node ();//Now regardless of whether the element has an element, but this element space-time, as the head, and then we add the new element in Node *p = this- >head;//with a cursor pointer node* val = new Node (e);//Then put the new Val to the end of the element P = this->gettail ();//now P points to the tail element, we put the element at the end of the P->setnext ( Val); Val set as the trailing element}//node* GetHead ();//Get the head pointer node* linklist::gethead () {return this->head;} node* Linklist::gettail () {node* p = this->head;while (P->getnext ()! = nullptr) {p = P->getnext ();//loop to the lastNode}return p;} node* pop (); Delete last node node* linklist::p op () {//with a cursor pointer node* p = this->gethead (); node* q = This->gethead ();//First determine if there are elements that can be deleted, judging by the condition that the first pointer is not an empty if (p->getnext () = = nullptr) {cout << " Event table is empty "<< Endl;return nullptr;} Loop to the last and penultimate while (P->getnext ()! = nullptr) {q = p;//gets the previous node P = P->getnext ();//Go to the next node}//if the end is not empty, the description also has elements, Then we'll remove the last one and return to the last Q->setnext (nullptr); Let's go. The second one is set to NULL, disconnect return p; Returns the pointer to the broken data}//bool listempty ();//Determines whether the empty list bool Linklist::listempty () {//Determines whether an empty identifier is a header pointer and a tail pointer is the same node, then represents an empty if ( This->gethead () = = This->gettail ()) {//No next node return true;} return false; The next non-empty header node}


Then we use a queue object to represent the queue of the bank window:

/** function: This implementation is the queue of our event * file: linkqueue.h* time: July 9, 2015 17:17:09*cutter_point*/#ifndef linkqueue_h#define linkqueue_ Hclass Qnode{int arrivaltime;//Time arrival time int duration;//time required to process the business qnode* next;//refers to the next node Public:qnode () {this-> ArrivalTime = 0;this->duration = 0;this->next = nullptr;} Qnode (qnode* e) {this->arrivaltime = E->arrivaltime;this->duration = E->duration;this->next = nullptr;} Set and Get methods void Setarrivaltime (int arrival) {This->arrivaltime = arrival;} int Getarrivaltime () {return this->arrivaltime;} void setduration (int dur) {this->duration = dur;} int getduration () {return this->duration;} void Setnext (qnode* n) {this->next = n;} qnode* GetNext () {return this->next;}}; Class linkqueue{//qnode* base;//initialized dynamically allocated storage qnode* front;//Queue header qnode* rear;//queue tail public:linkqueue ();//Initialize void EnQueue (qnode* e); Inserting Data Qnode deQueue (); Deletes a data bool Queueempty ();//Determines whether the queue is empty Qnode gethead ();//Gets the header element of the queue int length ();//set and get method void Setfront (qnode* qn) { This->front = qN }qnode* Getfront () {return this->front;} void Setrear (qnode* qn) {this->rear = QN;} qnode* Getrear () {return this->rear;}}; #endif

Realize:


/** function: This implementation is the queue of our event * file: linkqueue.h* time: July 9, 2015 17:17:09, July 10, 2015 15:18:58*cutter_point*/#include "LinkQueue.h" Linkqueue (); Initialize Linkqueue::linkqueue () {//Initialize queue when queue is FIFO//First we create a new empty node this->rear = This->front = new Qnode ();this-> Front->setnext (nullptr);//initialize with only one node, followed by nullptr}//to get the length of the queue int linkqueue::length () {///Because the first one is empty, So we judge the length of the queue is the length of the tail and header int length = 0; qnode* p = this->front;//uses a cursor as a pointer, pointing to the corresponding position while (P! = this->rear) {p = P->getnext (); ++length;} Return length;//Returns the length of the queue}//void EnQueue (qnode* e); Insert data void Linkqueue::enqueue (qnode* e) {//bar raw e inserted into the queue, because we are linked list, regardless of the queue is not full of problems, if it is a linear table, we also have to consider whether the queue is full of problems, because when initialized, Linear indicates a one-time application complete this->rear->setnext (e);//Then resets tail node this->rear = This->rear->getnext ();} Qnode DeQueue (); Delete a data, delete is the team first element Qnode Linkqueue::d equeue () {//This is the action of the queue Qnode e;//set two cursors qnode* p,* q;//First we have to judge if there is only one node, If there is only one valid node, then you have to update Rearif (This->getfront ()->getnext () = = This->getrear ()) {This->setrear (this-> Getfront ());//Set}//on the head node our operation is behind the head.The node is taken out and thrown to P = This->getfront (); q = P->getnext ();//Break head and first element pointer, bar pointer to the back of a node P->setnext (Q->getnext ()); Q->setnext (nullptr);//bar Q The value of this node is assigned to E and then returned, and the memory of Q is retrieved E.setarrivaltime (Q->getarrivaltime ()); E.setduration (q-> Getduration ()); E.setnext (nullptr);d elete Q;return e;} BOOL Queueempty ();//Determine if the queue is empty bool Linkqueue::queueempty () {//judgment is not empty because the head and tail are not pointing to a place if (this->getfront () = = This->getrear ()) {return true;} Else{return false;}} Qnode GetHead ();//Gets the first element of the queue, which simply returns a copy element of the first element Qnode Linkqueue::gethead () {Qnode e;e.setarrivaltime (this-> Getfront ()->getnext ()->getarrivaltime ()) E.setduration (This->getfront ()->getnext ()->getDuration ()); E.setnext (nullptr); return e;}


Our main function:

/** function: Suppose that a bank has 4 windows to receive customers externally. Because each window in a moment can only receive a customer, in the customer a large number of time to queue, for just enter the bank of the customer, if a window is free, you can go forward to transact business, if all the windows are not idle in the fewest number of Windows. It is now required to simulate a customer queuing situation for 4 windows within a certain time period of the bank. Here the customer arrives at the moment and the time to transact the business is random.  There is no use of threads here, in fact a better way is to use threads, a thread used to constantly produce Event (Customer arrival), a thread constantly handling the event, the customer's departure, as long as the bank does not ******** closed, when the event table is empty we wait () a thread, when the queue has a client's ******** when the thread notify, Knowing that the bank is closed, we interrupt the thread and end the exit ******************************************************************************* Documents: queue.cpp*: July 7, 2015 20:33:18, July 8, 2015 20:01:31, July 9, 2015 20:02:20, July 10, 2015 16:45:52, July 12, 2015 15:16:41* cutter_point*/#include "Event.h" #include "LinkList.h" #include "LinkQueue.h" #include <iostream> #include < ctime>using namespace Std;const static int COUNTER = 5;//altogether 4 Windows const static int max_time = 30;//This is the largest transaction time const Stati c int INTERVAL = 5;//a customer linklist ev;//event table appears every five minutes event en; Linkqueue* q[counter];//This is set as an array of pointers, each element inside the array is a pointer to Linkqueue qnode customer;int totaltime, Customernum, ClosetimE = 50;void Open_for_day () {cout << "************************************************************************" << endl;cout << "* * * * * * * * * * Bank" << Endl;cout < < "* * * * * * * * * * * * *" << endl;cout << "***************** "<< endl;//Initialize all data TotalTime = 0; Customernum = 0;en.setoccurtime (0); En.setntype (0);//Initialize all queues for (int i = 1; i < COUNTER; ++i) {Q[i] = new Linkqueue ();}} Open_for_day ()//For shortest queue int min_queue (linkqueue* q[counter]) {int max = 0, Usei = 1;for (int i = 1; i < COUNTER; ++i) {/ /Loop through all the queues to select the largest queue int testmax = Q[i]->length (); if (Testmax > Max) {max = Testmax;usei = i;}} Max is the largest return Usei in all queues after the loop is finished;} void Customer_arrived () {cout << "====================== a customer arrives ======================" << endl;//handles customer arrival events En. Ntype=0qnode *qe = new Qnode ()///Customer arrival time, required to process the businessTime, point to the next object int durtime, intertime;//One is the time required to process the business, one is the time required for the next customer to arrive ++customernum;//number of ++//parameters two random number, representing the time required to process the business, The next customer arrival time Durtime = rand ()% (max_time + 1);//This amount is [0 ~ max_time ()]intertime = rand ()% (INTERVAL + 1);//This is the next customer to go to the bank to wait for Time [0~interval (5)]//If the bank does not close, we want to generate the next event to arrive int t = en.getoccurtime () + intertime;if (T < closetime) {//Insert event table next event Ei;ei.setoccurtime (t); Ei.setntype (0); Ev.insert (EI);} int i = min_queue (q);//Get the shortest queue, note we have 1 to 4 queues, no 0 queues//bar events inserted into the shortest queue//First our event time (event arrival time) and execution time Qe->setarrivaltime ( En.getoccurtime ()); Qe->setduration (durtime);//Time Execution Time Q[i]->enqueue (QE);//bar QE is inserted into the list//to determine if the queue we are inserting is length 1, If it is represented before the insertion of this window is empty, this function//client departure event is to first calculate the customer's stay at the bank time, and then delete the customer from the queue after the check whether the queue is empty, if not empty, set a new head customer leave event En.setoccurtime ( En.getoccurtime () + durtime);//Set a new time arrival event En.setntype (i);//0 on behalf of the new customer arrives, 1 is 1th window customer left, 2 is 2nd window customer left, 3 is 3rd window customer left, 4 is ... , here is the customer arrival event, so it is 0if (q[i]->length () = = 1) {//Bar I queue departure event insert event table, etc will be used to calculate the window of the total customer time Ev.insert (en);}} Customer_arrived ()//Handle the Customer departure event, is to first calculate the customer's stay at the bank, and then remove the customer from the queue to see if the queue is empty, if not empty set a newThe head of the client left event void Customer_departure () {cout << "====================== a customer leaves ======================" << Endl Ntype > 0int i = en.getntype ();//Get the event type Q[i]->dequeue ();//bar to delete the queue, indicating that the customer left totaltime + = En.getoccurtime ()-customer.getarrivaltime ();//This is a customer stay event, does not include the processing of business time, this calculation is the customer wait time//If the customer is gone, the queue is not empty, Then set a new PAI customer if (q[i]->length ()! = 0) {Event E;customer = Q[i]->gethead ();//Get the customer e.setoccurtime of the Pai Tau (en.getoccurtime () + customer.getduration ()); Customers start to transact business hours + customer use time, that is, to the customer departure time E.setntype (i);//The window's Ev.insert (e);}} This function is used to generate a series of events, we first produce 20 event void Create_event () {for (int i = 1; i < 2; ++i) {customer_arrived ()}} void bank_smiulation (int closetime) {open_for_day ();//Bank Start Business create_event ();//Generate Event while (!ev.listempty ())//As long as the event table is not available {//node* p = ev.gethead ();//eject event from event list node* p = Ev.pop (); en = P->getevent ();//Remove time if (en.getntype () = = 0) {//Customer arrival Event Cust Omer_arrived ();} else{//client leaves Customer_departure ();}} while//calculate and output average stay time cout << "Average stay Time is:" << (float) totaltime/customernum<< Endl;} int main () {bank_smiulation (closetime);//ev.gethead ()->getevent (). Getoccurtime ();//cout << "Hello World" << Ev.gethead ()->getevent (). Getoccurtime () <<endl;return 0;}


Implementation results:












Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

"Data Structure" 3, Simulation Bank window queuing system--c++

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.