Elevator Controller
Low-Level Design: lesson 12 of 15
The car has a direction, and the direction answers the buttons.
Lesson 12 of 15 · 6 min
Elevator Controller
Step 1 of 8
The car is standing at floor 6 with no heading. idle is a real state, not a missing one.
The Idea
Model the car as a small state machine: idle, up, down, doors open. Pending floors live in a set, not a queue.
The controller never asks who pressed first. It asks what is next in the direction it is already travelling, and only reconsiders direction when nothing is left ahead.
Real-World Example
A hotel lift that sails past the lobby on its way to the ninth floor, then collects seven and four coming back down. The same button, pressed at the same moment, is answered differently because the car has a heading.
The Code
class Car:
def __init__(self, floor=0):
self.floor, self.direction, self.stops = floor, "idle", set()
def press(self, f):
self.stops.add(f) # a set, not a queue
if self.direction == "idle": # first request sets it
self.direction = "up" if f > self.floor else "down"
def next_stop(self):
ahead = [f for f in self.stops
if (f > self.floor) == (self.direction == "up")]
return (min if self.direction == "up" else max)(ahead) if ahead else None
car = Car(6); car.press(9); car.press(4)
print(car.direction, car.next_stop()) # up 9The Tradeoff
A directional sweep moves the building well but makes the floor behind you wait a full turn. Strict first-come order is fairer per button and far worse overall — cap the wait with a second car, not a fairer rule.
Your turn
Put the steps in the right order.
- The car keeps climbing, collecting the floors ahead of it in order
- A button press adds a floor to the pending set
- An idle car takes its direction from that first request
- next_stop considers only floors ahead of the car in its current direction
Mini quiz
1 / 3