I am trying to write code for simulating movement of single elevator. This was a question to me and was pretty straightforward as the use-case was explained properly. So the problem contains following data:
inputFloors : all floors elevator should go to. e.g. {5, 2, 9, 3, 8, 1}
currentFloor : current floor where elevator is standing/user is entering the elevator. e.g. 6
direction : direction of elevator movement like UP or DOWN.
Now since the user is entering at floor 6 and wants to go down then the route of the elevator should be 5, 3, 2, 1, 8, 9. That means the elevator should first go down the lesser floors in descending order and then go up the higher floors in ascending order. Similarly if the user wants to go up then the route should be 8, 9, 5, 3, 2, 1.
I wrote the code and it looked like a pretty simple use-case to me. But I wanted to see if there is any better way to do this. I am brushing up my c++ basics so this is the best solution i could think of.
My Code :
std::vector<int> singleElevatorSystem (int inputFloors[], int size, int currentFloor, string direction) {
std::vector<int> High, Low;
for (int i = 0; i < size; i++) {
if (currentFloor < inputFloors[i]) {
High.push_back (inputFloors[i]);
} else if (currentFloor > inputFloors[i]) {
Low.push_back (inputFloors[i]);
}
}
std::sort (High.begin(), High.end());
std::sort (Low.begin(), Low.end());
if (direction.compare("UP") == 0) {
High.insert(High.end(), Low.rbegin(), Low.rend());
return High;
} else if (direction.compare("DOWN") == 0) {
std::reverse (Low.begin(), Low.end());
Low.insert (Low.end(), High.begin(), High.end());
return Low;
}
}
int main () {
int inputFloors[] = {5, 2, 9, 3, 8, 1};
int currentFloor = 6;
//string direction("UP");
string direction("DOWN");
std::vector<int> outputFloors = singleElevatorSystem (inputFloors, 6, currentFloor, direction);
std::cout << "Elevator will stop at requested floors in sequence : ";
for (int i = 0; i < 6; i++) {
std::cout << outputFloors.at(i) << " ";
}
std::cin.get();
return 0;
}
I hardcoded the size of array and current floor value.
Any comments or updates please??