電梯控制算法(1)單電梯場景——簡單掃描算法
https://blog.csdn.net/nameofcsdn/article/details/106874615
在實際情況下,電梯並不需要掃描所有的樓層,只需要掃描有乘客進出電梯的樓層。
所以,我增加了2個全局變量,用來保存計算出來的電梯上下行的最上下的樓層。
#include <thread>
#include<time.h>
#define LEVEL 6
int flag[LEVEL + 1]; //1到Level層的外部輸入,取值爲0,1,2,3,其中0表示無乘客,1表示有乘客上行,2表示有乘客下行,3表示既有上行又有下行
int dest[LEVEL + 1]; //目的樓層的記錄,取值爲0,1,其中0表示不是目的地,1表示是目的地
int levelMax, levelMin; //levelMax是進出電梯最大樓層,levelMin是進出電梯最小樓層
void input()
{
int lev, fla;
while (cin >> lev >> fla) if (lev > 0 && lev <= LEVEL)
{
if (fla>0 && fla <= 3)flag[lev] = fla; //外部輸入
else dest[lev] = 1;//內部輸入
}
}
void upPull(int loc)//上行接客
{
flag[loc]--;
cout << "上行接客" << loc << endl;
}
void downPull(int loc)//下行接客
{
flag[loc] -= 2;
cout << "下行接客" << loc << endl;
}
void push(int loc)//送客
{
dest[loc] = 0;
cout << "送客" << loc << endl;
}
int getMax()
{
levelMax = 0;
for (int loc = 1; loc <= LEVEL; loc++)
{
if (flag[loc] || dest[loc])levelMax = max(levelMax, loc);
}
return levelMax;
}
int getMin()
{
levelMin = LEVEL + 1;
for (int loc = 1; loc <= LEVEL; loc++)
{
if (flag[loc] || dest[loc])levelMin = min(levelMin, loc);
}
return levelMin;
}
void run()
{
int loc = 1;
cout << " 當前樓層" << loc << endl;
while (1)
{
while (loc <= getMax())
{
if (flag[loc] == 1 || flag[loc] == 3)upPull(loc);
if (dest[loc])push(loc);
Sleep(1000);
if (loc<getMax())loc++;
else break;
cout << " 當前樓層" << loc << endl;
}
while (loc >= getMin())
{
if (flag[loc] == 2 || flag[loc] == 3)downPull(loc);
if (dest[loc])push(loc);
Sleep(1000);
if (loc > getMin())loc--;
else break;
cout << " 當前樓層" << loc << endl;
}
}
}
int main()
{
thread t1(input);
thread t2(run);
t1.join();
t2.join();
return 0;
}
優化點:
(1)電梯並不需要掃描所有的樓層,只需要掃描有乘客進出電梯的樓層。
(2)解決了之前代碼在上下行轉換時,重複顯示當前樓層的問題。
示例1:
示例2:
這個例子乍一看不對勁,實際上是對的。
當3樓上行乘客進入電梯後,如果一段時間之內不輸入,電梯就會直接去接別人了。
示例3:
在這樣的一個模擬程序中,我們並不知道每一次電梯開門出去了幾個人,這也是和實際情況吻合的。