離散事件模擬--銀行排隊時間模擬 微信:318175542
來源:程序員人生 發(fā)布時間:2015-07-24 09:51:03 閱讀次數(shù):4984次
在數(shù)據(jù)結(jié)構(gòu)中有個講述如何摹擬銀行排隊,終究算出每一個人平均的逗留時間。
這是需要數(shù)據(jù)結(jié)構(gòu)的知識。將銀行的每一個窗口看成是1個隊列,那末對每次來1個人,都需要從最短的隊列進行排隊。(其實更優(yōu)秀的做法是從最短的等待時間隊列來排隊)。
這里的做法是這樣的,首選在1個隊列中插入1個人,全部事件是事件驅(qū)動的,每次去檢查所有隊列,刪除那些業(yè)務(wù)用時已超越的人,然后選擇最短的隊列來插入1個人,也就是說,每次插入1個人之前就需要清除隊列中的人。然后再選擇適合的隊列來插入新的人。
#include <iostream>
#include <vector>
#include <deque>
#include <stdlib.h>
#include <time.h>
#include <numeric>
#include <limits>
using namespace std;
/*
摹擬1個離散時間情形
比如銀行的排隊系統(tǒng),記錄每個客戶的平均逗留時間
*/
/*
思路:假定銀行有多個窗口,那末每一個窗口就是每一個隊列,我們
記錄在規(guī)定時刻 或所有窗口再次為空的情況下結(jié)束事件的摹擬
*/
#define CloseTime 10000 //最長的摹擬事件是10000分鐘以后關(guān)閉事件的摹擬
typedef struct Record Record;
struct Record
{
int ArrivedTime;// 到達時間
int CostTime;// 辦理業(yè)務(wù)的時間
};
void Init(vector<deque<Record> >& win)
{
srand((unsigned)time(NULL));
int costtime = rand()%100;
Record customer;
customer.ArrivedTime =0;
customer.CostTime = costtime;
win[0].push_back(customer);
}
void Bank_Simulation(int WinNum)
{
double CustomerNum=1,TotalTime=0;
int CurTime=0;
int flag =1;
int LenDeque,index,i;
Record temp;
vector<deque<Record> > Win(WinNum);
srand((unsigned)time(NULL));
Init(Win);
while(flag)
{
flag = 0;
LenDeque = numeric_limits<int>::max();
for(i=0;i<Win.size();i++)
{
if(Win[i].size() == 0)
{
LenDeque = Win[i].size();
index = i;
continue;
}
else
{
flag =1;
while(Win[i].size())
{
temp = Win[i].front();
if(temp.ArrivedTime + temp.CostTime < CurTime)
{
Win[i].pop_front();
TotalTime += temp.CostTime;
}
else
break;
}
if(Win[i].size() < LenDeque)
{
LenDeque = Win[i].size();
index = i;
}
}
}
if(flag ==0)
break;
if(CurTime >10000)
break;
cout<<"===="<<endl;
int arrivetime = rand()%15;
temp.ArrivedTime = arrivetime+CurTime;
temp.CostTime = rand()%30;
CurTime = temp.ArrivedTime;
Win[index].push_back(temp);
CustomerNum++;
}
cout<<TotalTime<<endl;
cout<<CustomerNum<<endl;
cout<<TotalTime/CustomerNum<<endl;
}
int main()
{
Bank_Simulation(4);
return 0;
}
生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對您的學習有所幫助,可以手機掃描二維碼進行捐贈