電梯控制算法(4)單電梯場景——限層策略

電梯很多都有限層策略,主要是定差限層和高中低限層2種。

單電梯一般不怎麼需要限層,但是爲了更好的理解,還是寫一寫。

限層的實現:用avail數組記錄可達樓層,在輸入時直接屏蔽不可達樓層。

在輸入時屏蔽,而不是在運行時再跳過不可達樓層,是有道理的,有些電梯直接就是拿東西蓋住了,不可達的樓層就是按不了,或者高中低限層電梯,其他樓層根本就沒有對應按鈕,所以我的模擬思路是在輸入時進行屏蔽,這是合理的。

#include<iostream>
#include<queue>
#include<map>
#include<vector>
#include<string>
#include<windows.h>
#include<set>
#include<functional>
#include<set>
#include<math.h>
using namespace std;

#include <thread>
#include<time.h>

#define LEVEL 16
#define PARK 1  //空閒停靠樓層
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是進出電梯最小樓層
int avail[LEVEL + 1]; //可達樓層,取值爲0,1,其中0表示不是可達樓層,1表示是可達樓層

void input()
{
	int lev, fla;
	while (cin >> lev >> fla) if (lev > 0 && lev <= LEVEL)
	{
		if (avail[lev] == 0)continue;
		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;
}
bool isPark()//是否爲空閒狀態
{
	return getMax() <= 0 || getMax() > LEVEL;
}
int getMax2()//進出電梯最大樓層
{
	if (isPark())return PARK;
	return getMax();
}
int getMin2()//進出電梯最小樓層
{
	if (isPark())return PARK;
	return getMin();
}
void initAvail()
{
	for (int i = 1; i <= LEVEL; i++)
	{
		avail[i] = i % 2;
	}
}
void run()
{
	initAvail();
	int loc = 1;
	cout << "    當前樓層" << loc << endl;
	while (1)
	{
		while (loc <= getMax2())
		{
			if (flag[loc] == 1 || flag[loc] == 3)upPull(loc);
			if (dest[loc])push(loc);
			Sleep(1000);
			if (loc<getMax2())loc++;
			else break;
			cout << "    當前樓層" << loc << endl;
		}
		while (loc >= getMin2())
		{
			if (flag[loc] == 2 || flag[loc] == 3)downPull(loc);
			if (dest[loc])push(loc);
			Sleep(1000);
			if (loc > getMin2())loc--;
			else break;
			cout << "    當前樓層" << loc << endl;
		}
	}
}

int main()
{
	thread t1(input);
	thread t2(run);
	t1.join();
	t2.join();
	return 0;
}

這裏以只停奇數樓層爲例:

輸入8 0會被屏蔽,輸入8 3也會被屏蔽。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章