The Elevator Ride

Difficulty: ★ ★ ★ ☆

I recently stayed at a resort with a tall hotel tower, over 30 stories. As I rode the elevator up to my floor, I thought about how the lift worked like a pointer traversing an array: The floors are elements. Each stop going up represents a passenger’s desired destination, as do stops on the return trip. My programmer brain was on fire!

On the way up, elevators stop at floors based on user input. For example, four people walk into the elevator and select floors 3, 8, 11, and 13. The elevator rises to each floor sequentially.

On the return trip, the elevator collects people requesting to go down. Suppose people on floors 14, 10, 9, and 5 have pressed the down button. The elevator’s return trip collects these people, stopping at the given floors on the ride down, ending at the lobby.

Creating an elevator simulation would be fun, but a beast if you code all the details (passengers on/off, floors requested). Rather than burden you with such a complex ordeal, I have a simpler proposal:

For this month’s Exercise your task is to code a simple elevator simulation. Assume a building has 15 floors — like a 15-element array. Assume eight passengers are wanting to ride the elevator, either alone or in groups. They desire to go up from the lobby or return to the lobby from various floors.

Your task is to output a map of the simulation, showing the 15 floors and each stop requested on the way up followed by each stop requested on the way down. Here is sample output from my solution, which illustrates one way to solve the puzzle:

     Floor:  1   2   3   4   5   6   7   8   9  10  11  12  13  14  15 
  Going up:          >                   >           >       >         
Going down:                  <               <   <               <

Above, passengers on the ride up request stops on the 3rd, 8th, 11th, and 13th floors. On the return trip, the elevator visits floors 14, 10, 9, and 5 to collect passengers on the ride down. Never mind who exits or enters on which floor; the program need not be that complex.

You can code your solution however you like, but in my solution I use only a single array with 15 elements, one for each floor. Random numbers determine the floor requests both up and down.

Keep in mind that multiple passengers may get off or arrive at a single stop, going up or going down. So it's unnecessary to ensure that the elevator always have eight stops. In fact, it could have only one stop going up or down depending on the random requests, though such an occurrence is highly unlikely.

Click here to read my solution. Before then, please try this Exercise on your own. Don't leave those poor people stranded!

2 thoughts on “The Elevator Ride

  1. That’s why I eliminated the lobby (zero) as a concern. As an anglophile, I’m keenly aware that our “second floor” in the US is your “first floor” in the UK. Regardless, those people need to get off the lift!

Leave a Reply