Dispatch an elevator

An office building has two elevators, A and B. Someone presses Up or Down on a floor. The controller chooses which elevator answers the call.

Each elevator has a current floor and a target floor. If these are equal, the elevator is idle. Otherwise, it moves toward its target. Assume that the call and all floors are valid and both elevators are working.

Travel rule. An idle elevator goes straight to the call. A moving elevator can stop for a call on its current route when the call floor is strictly ahead of it, no farther than its target, and the pressed direction matches its movement. It then travels straight to the call. In every other case, it first reaches its target and then travels to the call. Count one floor of travel for each floor crossed. For example, abs(2 - 5) = 3.

Choice rule. The elevator with the shorter travel distance answers. If their distances are equal, A answers.

For example, A is idle on floor 4. B is on floor 9, traveling down to floor 1. Someone on floor 6 presses Down. A travels 2 floors; B stops on its current route after 3 floors. The controller chooses A.

Your task. In pseudocode or flowcharts, design these two procedures:

  1. Travel Distance: given one elevator’s floor and target, the call floor, and the pressed direction, return its travel distance to the call.
  2. Choose Elevator: given both elevators and the call, call Travel Distance for each elevator and return A or B.

Name each procedure and state its inputs and output. Then complete Table 1. Show both distances and the chosen elevator. An elevator is written as current floor → target floor.

Table 1: Calls to trace through the dispatch design.
Case A B Call Distance A Distance B Choice
On the way 2 → 2 7 → 0 floor 5, Down
Moving away 2 → 2 7 → 12 floor 5, Down
Equal distances 3 → 3 9 → 9 floor 6, Up

For a moving elevator, compare the call floor with both its current floor and its target. If it cannot stop on the way, add the distance to its target to the distance from that target to the call.