# Function simulating single elevator movement

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.

As a C++ learning exercise, you will benefit from creating an Elevator class in this case. Make it a class that has a the current floor and direction as a data members (those are the current states of the elevator), and a function PlanRoute that gets input floors as input, and returns the output floors.

The h-file will look something like this:

class Elevator {
public:
Elevator();
void setCurrentFloor(int currentFloor);
void setDirection(bool goingDown);
std::vector<int> planRoute(const std::vector<int>& inputFloors)
private:
bool goingDown;
int currentFloor;
}

• as part of my elevator system design i did the same as u mentioned. But as part of coding, i was asked to code just the function that can be executed given the input route, direction and current floor. Thanks for help though. – Puneet Mittal Feb 9 '16 at 15:40