Skip to content

Case study: Elevator system

Difficulty: Advanced

Key concepts

  • car state machine
  • legal transitions
  • collective control
  • dispatch rule
  • function pointer
  • tie-break
  • discrete-time simulation
  • deterministic tests
  • seeded random runs
  • express cars
  • maintenance mode
  • How to model an elevator car as a small state machine, with one function through which every change of state passes, so that a car moving with its doors open is a bug that throws at once rather than a state that quietly exists.
  • What collective control is (stop for everything on the way, turn only when nothing is left ahead), what it guarantees, and what it does not.
  • Why time in this design is a number that only a test moves, and how that makes every run, even a random one, repeatable to the tick.
  • How to make the dispatch rule a parameter without building a class hierarchy: a plain noexcept function pointer, and when a Strategy class or std::function would earn its place instead.
  • How to choose a car deterministically, with a tie-break that every rule shares.
  • How a change (express cars, and taking a car out of service) lands: one filter in the building, and a car that hands back its calls before it parks.

This page follows the order in How to approach a case study. It assumes State machines and invalid-state prevention and Strategy. The first gives the idea of states, events, and a table of legal moves; the second gives the idea of a rule chosen from outside. This page needs both at once, plus a clock that the program controls.

“We manage a ten-storey office building with two cars, and we want to replace the old controller with something we can simulate and test before it goes near the real shafts. People complain that a car goes right past them, or that the far car comes when the near one was free. Can you design the part that decides where each car goes?”

Two complaints, and both are about choices: which floor a car serves next, and which car answers a call. Neither is about motors or doors. That is a hint about scope: the design is the decision-making, and the hardware is something it talks to.

Each question is here because its answer changes the design.

Question Answer (from the team) What it changes
What buttons are there? Up and down on each landing (no up on the top floor, no down on the ground floor), and a floor panel in each car. Two kinds of request: a hall call (floor and direction) and a car call (car and floor).
When a car is going up, should it stop for someone who wants down? No. It picks them up on the way back. Collective control: a hall call counts only in the car’s direction.
Who decides which car answers a hall call? The controller, at the moment the button is pressed. We want to try different rules and compare them. One car per hall call, chosen by a rule that is a parameter of the building.
May a call move to another car later? Not in normal service. A hall call is given once; only a change (maintenance, below) hands it on.
How fast do cars move, and how long do the doors stay open? For the simulation, one floor per step and a fixed number of steps with the doors open. Time is a count of ticks. Speed and door time are settings, not clocks.
Do we model people: how many get in, how heavy the car is? Not yet. We care about where the cars go. No passengers, no capacity. A stop is a flag, not a list of people.
What should happen with a request that makes no sense? Refuse it and say why: floor 12, up on the top floor, a car that does not exist. Every request returns an answer with a reason, and a refused one changes nothing.
Must two runs with the same inputs behave the same? Yes. We want to replay a complaint exactly. No threads, no wall clock, no randomness inside the controller. Ties are broken by a fixed rule.
Is this the safety system? No. Door sensors, brakes, and limits are separate hardware. Out of scope, and the page says so. “Never move with the doors open” is still an invariant of the model.

Three answers decide the shape. “Picks them up on the way back” is the collective control rule, which lives in the car. “Try different rules” makes the choice of car a parameter, which lives in the building. “Replay a complaint exactly” rules out threads and clocks, and turns time into something a test moves by hand.

Confirmed:

  • A building with a number of floors (0 is the lobby) and one or more cars, each starting on a floor.
  • Hall calls and car calls, checked and refused with a reason.
  • Each car moves one floor per tick, keeps its doors open for a set number of ticks at each stop, and follows collective control.
  • Each hall call goes to one car, chosen by a rule set when the building is built: nearest_car or least_busy.
  • A simulation that advances only when tick() is called.

Assumed (to confirm with the team; see Assumptions):

  • Pressing a lit button again changes nothing.
  • A request that the open doors already serve (a car call for the floor the car is open on, or a hall call there in the car’s direction) is served at once, with no extra stop.
  • A building has at most 26 cars, named A to Z, because the traces use one letter per car.

Out of scope: passengers, weight, and capacity; real time, speed, and acceleration; door obstruction, safety circuits, fire service, and emergency stops; the motor and door drivers; several controllers working together. Express cars and maintenance arrive as a change, below.

Functional requirements.

  • FR-1 Requests. A hall call names a floor and a direction; a car call names a car and a floor. A floor that does not exist, up on the top floor, down on floor 0, or a car that does not exist is refused with a reason. A lit button pressed again is accepted and changes nothing.
  • FR-2 One car per hall call. Each accepted hall call is given to exactly one car, chosen by the building’s rule, with ties broken the same way every time.
  • FR-3 Movement. A car moves at most one floor per tick, opens its doors at each stop for the set number of ticks, and never moves with its doors open.
  • FR-4 Collective control. A moving car stops at every car stop and every hall call in its direction on its way, goes on to the farthest stop ahead, and only then turns round. A hall call the other way is served on the way back, or where the car turns.
  • FR-5 Every request is served. Each accepted request is served in a bounded number of ticks.

Non-functional requirements.

  • NFR-1 Deterministic. The same configuration and the same requests at the same ticks give the same trace, on every run and every platform. No threads, no clocks.
  • NFR-2 No invalid car state. A car is always in one of four named states, every change goes through one check, and an illegal change throws std::logic_error.
  • NFR-3 Refusals change nothing. A refused request, or one that fails part way (say, out of memory), leaves every car as it was.
  • NFR-4 Serving does not allocate. A car’s table of stops is made once, when the car is built, so adding or serving a stop never allocates.
  • NFR-5 Single-threaded, on purpose. One thread calls everything, and the documentation says so.

FR-4 is the first complaint (“a car goes right past me”) turned into a rule. FR-2 and the choice of rule are the second (“the far car came”). NFR-1 is what makes it possible to test either.

The tests are named after these criteria. See Use cases, user stories, and acceptance criteria.

UC-1 Press a button.

  • AC-1.1 A hall call is given to exactly one car.
  • AC-1.2 A car call adds a stop to that car only.
  • AC-1.3 A floor that does not exist is refused, with a reason.
  • AC-1.4 A direction that leads nowhere is refused.
  • AC-1.5 A car that does not exist is refused.
  • AC-1.6 Pressing a lit button again changes nothing.
  • AC-1.7 A bad building is refused when it is built: fewer than two floors, a car starting off the floors, doors open for no ticks, no cars, more than 26 cars, or no rule.

UC-2 Move a car.

  • AC-2.1 A car moves one floor per tick, and opens its doors in the tick it arrives.
  • AC-2.2 The doors stay open for the set number of ticks.
  • AC-2.3 A car never moves with its doors open.
  • AC-2.4 Only the legal transitions are allowed.
  • AC-2.5 An idle car with nothing to do stays put.
  • AC-2.6 A request that the open doors already serve is served at once.

UC-3 Serve stops in order.

  • AC-3.1 A car finishes its direction before reversing.
  • AC-3.2 A car stops for a hall call in its direction on the way.
  • AC-3.3 A hall call the other way is passed, and served on the way back.
  • AC-3.4 A car turns at a call the other way when nothing is ahead.
  • AC-3.5 Up and down calls on one floor get one opening each.
  • AC-3.6 An idle car opens for a call on its own floor.

UC-4 Choose a car.

  • AC-4.1 nearest_car follows the car’s route, and counts zero for a car open on the floor going the same way.
  • AC-4.2 A hall call goes to the car with the lowest cost.
  • AC-4.3 Ties go to the nearer car, then to the lower index.
  • AC-4.4 least_busy takes the car with fewer stops.
  • AC-4.5 least_busy ignores the call.

UC-5 Run the building.

  • AC-5.1 In seeded random runs, every accepted request is served within a bound.
  • AC-5.2 The same inputs give the same trace.
  • AC-5.3 Seeded random runs keep every invariant on every tick.

Each invariant names the code that keeps it. See Invariants.

  • INV-1 One floor per tick. A car’s floor changes by at most one in a tick. Kept by Car::step, which calls move_one_floor at most once.
  • INV-2 Never move with the doors open. A car whose doors are open at the start of a tick does not change floor in it. Kept by Car::step: the doors_open case only counts down and decides; it never moves.
  • INV-3 Only legal transitions. Every change of state is one that legal_transition allows. Kept by Car::go, the only code that writes state_.
  • INV-4 Never pass a stop ahead. A car that arrives at a floor with a car stop, or a hall call in its direction of travel, opens its doors there in the same tick. Kept by move_one_floor, which asks wants_to_stop_here on every arrival.
  • INV-5 A hall call belongs to one car. No two cars hold the same hall call. Kept by Building::hall_call, which looks for the call in every car before choosing one.
  • INV-6 Refused means unchanged. Kept by the order inside each request: every check, then building the answer (which may allocate), then the one change to a car, which cannot fail.

The random tests check INV-1 to INV-4 for every car after every tick, using a copy of the car taken before it; see Tests.

The nouns from the answers: building, floor, car, door, button, hall call, car call, direction, rule, step, passenger, controller. Filtered:

  • Building is the Building: it owns the cars, checks requests, chooses a car for each hall call, and moves time.
  • Floor is an int, named Floor. There is no Floor class, because a floor has no behaviour of its own; what waits on it is kept by the cars.
  • Car is a Car: its floor, its state, its direction, and its stops.
  • Door is not an object. It is open in exactly one state of the car, doors_open, with a count of ticks left. A separate Door object would be a second place that says whether the doors are open, and the two could disagree.
  • Button, hall call, and car call become a HallCall value (floor and direction), a floor for a car call, and one Stops record of three flags per floor inside each car.
  • Direction is an enum class Direction { up, down }.
  • Rule is a CostRule: a pointer to a function that scores one car for one call.
  • Step is a tick: Building::tick() calls Car::step() on every car.
  • Passenger is out of scope. Controller is the whole program.
Classes in step 1. Filled diamond: owns. Plain arrow: uses
Text description of the diagram

Building owns a vector of Car, holds a CostRule (a pointer to one of the dispatch functions), the number of floors, and the tick count. It offers hall_call and car_call, which return an Answer, plus tick, settled, and describe, and privately choose_car. Car holds its name, the number of ticks its doors stay open, its floor, its CarState, its direction, the ticks left with the doors open, and a vector of Stops, one per floor, each with three flags: car, up, and down. Car offers add_car_stop, add_hall_call, step, pending, and farthest_stop, and privately wants_to_stop_here, serve_here, and go. CarState is an enumeration of idle, moving_up, moving_down, and doors_open. HallCall is a floor and a direction. Answer is accepted, a text, and an optional car index. The dispatch functions nearest_car and least_busy each score one car for one call; the building’s rule points to one of them.

Diagram source (Mermaid)
classDiagram
class Building {
  -int floors_
  -CostRule rule_
  -vector~Car~ cars_
  -int now_
  +hall_call(Floor, Direction) Answer
  +car_call(index, Floor) Answer
  +tick()
  +settled() bool
  +describe() string
  -choose_car(HallCall) size_t
}
class Car {
  -string name_
  -int door_ticks_
  -Floor floor_
  -CarState state_
  -Direction direction_
  -int door_ticks_left_
  -vector~Stops~ stops_
  +add_car_stop(Floor)
  +add_hall_call(HallCall)
  +step()
  +pending() int
  +farthest_stop(Direction) optional~Floor~
  -wants_to_stop_here() bool
  -serve_here()
  -go(CarState)
}
class Stops {
  +bool car
  +bool up
  +bool down
}
class CarState {
  <<enumeration>>
  idle
  moving_up
  moving_down
  doors_open
}
class HallCall {
  +Floor floor
  +Direction direction
}
class Answer {
  +bool accepted
  +string text
  +optional~size_t~ car
}
class dispatch {
  <<functions>>
  +nearest_car(const Car&, HallCall) int
  +least_busy(const Car&, HallCall) int
}
Building *-- Car : cars_
Car *-- Stops : one per floor
Car --> CarState : state_
Building --> dispatch : rule_ points to one
Building ..> HallCall : makes
Building ..> Answer : returns

Ownership is short to say. The Building owns its cars by value, in a std::vector<Car>, and nothing else owns a car. A Car owns its table of stops. The rule is a pointer to a function, which has no lifetime to manage: functions exist for the whole program. Nothing in this design is shared, and nothing is on the heap except what the vectors and strings allocate inside themselves.

The design below is step 1 of the example, the complete answer to FR-1 … FR-5. Express cars and maintenance are added in When the requirements change.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

car.hpp
// What a car is doing between two ticks. The doors are open in exactly one
// state, so "never move with the doors open" is the same as "never change
// floor in a tick that starts in doors_open".
enum class CarState {
idle, // doors closed and not travelling: waiting, or about to decide
moving_up, // doors closed, travelling up: the next tick moves it one floor up
moving_down, // the same, downwards
doors_open, // stopped at a floor with the doors open for a fixed number of ticks
};
// True if a car may go straight from `from` to `to`. Car::go asks this
// before every change of state, so the table below is the whole state
// machine: any other change is a bug and throws std::logic_error.
// idle -> moving_up, moving_down, doors_open
// moving_* -> doors_open (a moving car stops only to open its doors)
// doors_open -> idle, moving_up, moving_down, doors_open (open again)
[[nodiscard]] bool legal_transition(CarState from, CarState to) noexcept;

Four states, and the doors are open in exactly one of them. That one fact carries a lot: “never move with the doors open” becomes “never change floor in a tick that starts in doors_open”, which is a single case in a single function to check. There is no bool doors_open anywhere that could disagree with the state.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

car.cpp
bool legal_transition(CarState from, CarState to) noexcept {
switch (from) {
case CarState::idle:
return to == CarState::moving_up || to == CarState::moving_down ||
to == CarState::doors_open;
case CarState::moving_up: // two case labels, one body: both moving states
case CarState::moving_down:
return to == CarState::doors_open;
case CarState::doors_open:
return true; // close and wait, close and leave either way, or open again
}
return false; // not reached: every state is handled above
}

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

car.cpp
// Every change of state goes through here, so an illegal one is caught at
// the moment it happens. The check comes first: if it throws, the car is
// still in its old state.
void Car::go(CarState next) {
if (!legal_transition(state_, next)) {
throw std::logic_error("illegal transition " + to_string(state_) + " -> " + to_string(next));
}
state_ = next;
}
The states of one car in step 1, and what moves it between them
Text description of the diagram

A car starts idle with its doors closed. From idle it goes to moving up if it has stops above and none on its floor, to moving down if it has stops below and none on its floor, and to doors open if there is a stop on its own floor. A moving car, up or down, can only go to doors open, when it arrives at a stop. When the doors have been open for the set number of ticks, the car decides: it opens again for a call the other way on this floor if nothing is left ahead, sets off up or down if it has stops that way, or goes idle if it has nothing to do. There is no arrow from moving up to moving down or back, and none from moving to idle: a moving car cannot reverse, or stop without opening its doors.

Diagram source (Mermaid)
stateDiagram-v2
[*] --> idle : built, doors closed
idle --> moving_up : stops above, none here
idle --> moving_down : stops below, none here
idle --> doors_open : a stop on this floor
moving_up --> doors_open : arrived at a stop
moving_down --> doors_open : arrived at a stop
doors_open --> doors_open : dwell over, a call the other way here, nothing ahead
doors_open --> moving_up : dwell over, stops above
doors_open --> moving_down : dwell over, stops below
doors_open --> idle : dwell over, nothing to do

The table of legal moves is the whole state machine, written as one function, as in Writing the table as code. Car::go is the only code that writes state_, and it asks the table first. If a later change to step tried to send a moving car straight into reverse, the very first test to reach that line would throw std::logic_error("illegal transition up -> down"), rather than letting a car do something no real car can.

Why an enum class and not a std::variant of state structs, as the ATM uses? Because the states of a car carry almost no data of their own. Only doors_open has something extra, the count of ticks left, and it is one int. A variant earns its cost when each state holds different data that must not exist in the others, such as a bank session that exists only while signed in. Here the floor, the direction, and the stops exist in every state, so an enum plus a transition table says everything, more simply.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

car.hpp
// One car. The building checks every request before passing it on; the
// car checks floors again (std::out_of_range) so that it can never index
// outside its own table of stops. The car is copyable, which lets a test
// keep a copy from before a tick and compare it with the car after it.
class Car {
public:
// Throws std::invalid_argument for fewer than two floors, a start floor
// outside the building, or doors that stay open for less than a tick.
Car(std::string label, int floors, Floor start, int door_ticks);
[[nodiscard]] const std::string& name() const noexcept { return name_; }
[[nodiscard]] Floor floor() const noexcept { return floor_; }
// How many floors the building has (one entry per floor in stops_).
[[nodiscard]] int floors() const noexcept { return static_cast<int>(stops_.size()); }
[[nodiscard]] CarState state() const noexcept { return state_; }
// The way the car is going, or was last going. It still has a value
// when the car has no stops, so treat it as a hint in that case.
[[nodiscard]] Direction direction() const noexcept { return direction_; }
// Throw std::out_of_range for a floor that is not in the building.
[[nodiscard]] bool has_car_stop(Floor floor) const;
[[nodiscard]] bool has_hall_call(HallCall call) const;
// Stops still to make: car stops plus hall calls, each counted once.
[[nodiscard]] int pending() const noexcept;
[[nodiscard]] bool has_stops() const noexcept { return pending() > 0; }
// The farthest floor beyond the car's floor, in `direction`, that has
// any stop (car stop, up call, or down call); empty if there is none.
[[nodiscard]] std::optional<Floor> farthest_stop(Direction direction) const noexcept;
// Add a stop. If the doors are already open on that floor (and, for a
// hall call, the car is going that way), the request is served at once
// and nothing is stored. Throw std::out_of_range, changing nothing, for
// a floor that is not in the building.
void add_car_stop(Floor floor);
void add_hall_call(HallCall call);
// One tick of simulated time. See car.cpp for what each state does.
void step();
private:
// What is waiting on one floor. One of these per floor, made in the
// constructor, so adding or serving a stop later never allocates.
struct Stops {
bool car = false; // someone inside wants to get out here
bool up = false; // someone here wants to go up
bool down = false; // someone here wants to go down
};
static bool& call_flag(Stops& stops, Direction direction) noexcept;
static bool call_flag(const Stops& stops, Direction direction) noexcept;
Stops& stops_at(Floor floor);
[[nodiscard]] const Stops& stops_at(Floor floor) const;
[[nodiscard]] bool wants_to_stop_here() const;
[[nodiscard]] std::optional<Direction> next_direction() const noexcept;
void open_doors();
void serve_here();
void leave_floor();
void move_one_floor();
void go(CarState next);
std::string name_;
int door_ticks_; // how many ticks the doors stay open at each stop
Floor floor_;
CarState state_ = CarState::idle;
Direction direction_ = Direction::up;
int door_ticks_left_ = 0; // counts down while the doors are open
std::vector<Stops> stops_; // index = floor number
};

A car keeps its stops as one Stops record per floor: three flags, for someone inside who wants to get out there, someone waiting to go up, and someone waiting to go down. The vector is made once, in the constructor, with one entry per floor, and never grows or shrinks. Adding a stop sets a flag; serving it clears one. That is NFR-4: no stop ever allocates, so neither adding nor serving can fail for lack of memory, and the car never has to keep a list in order.

The flags also make “pressing a lit button again changes nothing” (AC-1.6) free: setting a flag that is already set is the same as not setting it. A list of requests would need a search for duplicates.

direction() deserves its comment. A car that has nothing to do still remembers which way it was last going, because the next thing it does depends on it (an idle car faces the way it was going). Code outside the car should treat it as a hint when the car has no stops, and nearest_car does.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

car.cpp
// One tick. Each state does one thing:
// doors_open count down; when the count reaches zero the doors close
// and the car decides what to do (leave_floor)
// idle if anyone is waiting on this floor, open the doors;
// else if there are stops elsewhere, set off and move a floor
// moving_* move one floor, and open the doors if this floor is a stop
// The car moves only in the last two cases, when its doors are closed.
void Car::step() {
switch (state_) {
case CarState::doors_open:
--door_ticks_left_;
if (door_ticks_left_ > 0) return; // still open for this tick
leave_floor();
return;
case CarState::idle: {
if (!has_stops()) return;
const Stops& here = stops_at(floor_);
if (here.car || here.up || here.down) {
// An idle car has no trip to keep to, so it answers the people
// on its own floor first, turning to face their call if needed.
if (!here.car && !call_flag(here, direction_)) direction_ = opposite(direction_);
open_doors();
return;
}
// There are stops, none of them here, so next_direction has a
// value; value() would throw std::bad_optional_access if not.
direction_ = next_direction().value();
go(moving(direction_));
move_one_floor();
return;
}
case CarState::moving_up:
case CarState::moving_down:
move_one_floor();
return;
}
}

step does one thing per tick, and which thing depends only on the state. The helpers it calls are short and live beside it in car.cpp:

  • move_one_floor changes the floor by one in the car’s direction, then asks wants_to_stop_here; if the answer is yes, it calls open_doors. Arriving and opening happen in the same tick.
  • open_doors goes to doors_open, starts the count, and calls serve_here.
  • leave_floor, called when the count reaches zero, opens again if wants_to_stop_here says so (a call the other way, with nothing ahead), otherwise sets off in next_direction, otherwise goes idle.
  • next_direction keeps the car’s direction while there is anything ahead, otherwise turns round if there is anything behind, otherwise has no value.
How this code works: Car A in the step 1 demo, tick by tick

The step 1 demo builds ten floors with doors open for 2 ticks, car A at 0 and car B at 9. Before the first tick, A has a car stop at 7 and the hall call 4 up. At tick 5 someone inside presses 2. Each row is one call to A.step(); the last column is what the demo prints for A after that tick.

Tick State at the start What step does Printed after the tick
1 idle at 0 Nothing on floor 0. next_direction is up (stops ahead), so go(moving_up) and move to 1. Floor 1 is no stop. A 1 up [4^ 7]
2, 3 moving_up Move to 2, then to 3. Neither is a stop. A 3 up [4^ 7]
4 moving_up Move to 4. wants_to_stop_here: an up call, and the car is going up. Open; serve_here clears 4^. A 4 open [7]
5 doors_open Count 2 to 1: still open. After this tick, the demo presses 2 in car A: a car stop behind the car. A 4 open [7]
6 doors_open Count 1 to 0. leave_floor: no reason to open again; 7 is ahead, so go(moving_up). It does not move yet. A 4 up [2 7]
7, 8 moving_up Move to 5, then to 6. Floor 2 is behind and plays no part. A 6 up [2 7]
9 moving_up Move to 7: a car stop. Open; serve_here clears 7, finds nothing ahead, and turns the car to face down. A 7 open [2]
10 doors_open Count 2 to 1. A 7 open [2]
11 doors_open Count 1 to 0. Going down, 2 is ahead, so go(moving_down). A 7 down [2]
12–15 moving_down Move to 6, 5, 4, and 3. A 3 down [2]
16 moving_down Move to 2: a car stop. Open, and clear it. A 2 open []
17 doors_open Count 2 to 1. A 2 open []
18 doors_open Count 1 to 0. Nothing anywhere: go(idle). A 2 idle []

Three things to notice:

  1. The doors are open for exactly two printed ticks at each stop (4 and 5, 9 and 10, 16 and 17), and in the tick they close the car only decides; it moves on the next one. So the car is printed on a stop’s floor for three ticks (arriving, open, deciding), and a stop makes it two ticks later than passing the floor would.
  2. The stop at 2 waited. It was pressed at tick 5 with the car at 4 going up, and served at tick 16, after the car had finished its trip up to 7. That is FR-4 working, and it is the price of FR-4: a stop behind the car waits for the turn.
  3. Every change of state went through go. The transitions in this run were idle to moving up, moving up to doors open, doors open to moving up, doors open to moving down, moving down to doors open, and doors open to idle. Each one is in the table.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

car.cpp
// The collective control rule, asked on arrival at a floor: stop for a car
// stop, or for a hall call in the car's direction. A hall call the other
// way makes the car stop only if nothing is left ahead, because this floor
// is then where the car turns round anyway.
bool Car::wants_to_stop_here() const {
const Stops& here = stops_at(floor_);
if (here.car || call_flag(here, direction_)) return true;
return call_flag(here, opposite(direction_)) && !farthest_stop(direction_);
}
// With the doors open: the people inside who wanted this floor get out,
// and the people waiting to go the car's way get in. Only if that call
// was not there and nothing is left ahead does the car turn round here,
// and then it takes the people waiting to go the new way.
void Car::serve_here() {
Stops& here = stops_at(floor_);
here.car = false;
bool& same_way = call_flag(here, direction_);
if (same_way) {
same_way = false; // a call the other way, if any, waits for leave_floor
return;
}
if (!farthest_stop(direction_)) {
direction_ = opposite(direction_);
call_flag(here, direction_) = false;
}
}

This is the rule the first complaint asked for, and it is two short functions.

wants_to_stop_here is asked on every arrival, and again when the doors are about to close. A car stops for a car stop on this floor, or a hall call here in its direction. A hall call the other way makes it stop only if nothing at all is left ahead, because then this floor is where it turns round anyway.

serve_here runs as the doors open. It clears the car stop, and the hall call in the car’s direction if there is one. If there was no such call and nothing is ahead, the car turns round here, and the people waiting to go the new way get in too. When both an up and a down call wait on one floor, the car serves them in two openings, one per direction (AC-3.5), so the direction lantern is never wrong for the people getting in.

What collective control guarantees, in this model:

  • A car never passes a stop ahead in its direction. Every arrival asks wants_to_stop_here, and a car stop or a call in the direction of travel always says yes (INV-4). The random tests check this on every tick.
  • A car finishes its direction before it turns (AC-3.1). It turns only when farthest_stop finds nothing ahead.
  • Every stop is served before the car turns round a third time. A sweep ends at the farthest stop in the car’s direction, and that is never beyond the end of the building, so new requests cannot keep a car going one way for ever. A stop ahead is served in the current sweep. A car stop behind the car, or a call the other way, is served on the way back. A call behind the car in its own direction is the worst case: the car goes on to the end of this sweep, turns, goes to the end of the next, turns again, and arrives. That is the rest of one sweep, a whole sweep, and part of a third. Because the call is behind the car, the two partial sweeps together cover at most the height of the building, so in a building of n floors no stop waits for more than 2 × (n − 1) floors of travel, plus the stops on the way.

What it does not guarantee:

  • The shortest waits. It is a simple, predictable rule, not an optimiser. A person just behind a car going up may wait for two whole sweeps.
  • Anything about people. There are no passengers in this model, so no “the car is full, skip this call”, no “this person has waited too long”, and no counting of who got in.
  • Capacity or load. A car never refuses a stop because it is full.

The building has no clock and no thread. Building::tick() adds one to now_ and calls step() on each car, and that is the only way time passes. A test advances time by calling tick(), as many times as it likes, as fast as the processor runs. This is a discrete-time simulation: the world changes only at whole steps, and between steps nothing happens.

That choice is what makes NFR-1 true, and it is what makes the tests possible at all. A test of “the doors stay open for exactly two ticks” calls tick() and looks, with no sleeping and no tolerance for a slow machine. A trace of 600 ticks takes a moment, not ten minutes. And because nothing inside the controller is random, threaded, or read from a clock, the same requests at the same ticks always give the same trace: AC-5.2 runs one seeded random run twice and compares the two traces line by line.

The real controller would still have a timer. It would call tick() from it, at whatever rate a floor takes, and pass the sensors’ events in as requests. The decision-making does not change; only the thing that calls it does. See A real-time thread per car for what goes wrong when the timer is inside the design instead.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

dispatch.hpp
// Why a plain function type, and not a Strategy class or std::function:
// the curriculum asks for more than one dispatch rule, chosen when the
// building is set up, so the rule must be a parameter. But a rule is one
// question ("how costly is it for this car to take this call?") with no
// memory of its own, so a pointer to a function is enough. A Strategy
// interface would add a class per rule and the question of who owns the
// rule object; std::function would allow rules that capture state, which
// none of these needs. If a later rule needs state (say, traffic learned
// over a day), std::function or an interface is the next step.
//
// `noexcept` is part of the type: only functions that promise not to throw
// fit, so choosing a car can never fail half-way through a change.
// Lower is better. The score must not depend on anything but the car and
// the call, so the same building state always gives the same choice.
using CostRule = int (*)(const Car& car, HallCall call) noexcept;
// Floors the car would travel before it reaches the call, following its
// collective control route (an estimate: see dispatch.cpp).
[[nodiscard]] int nearest_car(const Car& car, HallCall call) noexcept;
// How many stops the car still has, wherever they are: spreads the work,
// at the price of sometimes sending a far car past a near one.
[[nodiscard]] int least_busy(const Car& car, HallCall call) noexcept;

A rule answers one question: how costly is it for this car to take this call? Lower is better. The building asks it once per car and takes the lowest. Both rules are free functions with the same signature, and CostRule is the type of a pointer to such a function. noexcept is part of that type, so only a function that promises not to throw can be stored there, and choose_car, which is noexcept itself, can call the rule without any chance of an exception in the middle of a choice.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

dispatch.cpp
// Three cases:
// 1. The car has no stops: it comes straight to the call.
// 2. The call is on the car's way: ahead of it (or here with the doors
// open) and going the same way. The car stops there as it passes.
// 3. Otherwise the car first goes on to its farthest stop ahead (the
// call's floor counts if it is ahead), turns, and comes back.
// Case 3 is an estimate: it follows the route only as far as the first
// turn, then counts straight from there to the call, which is not always
// the way the car really goes.
// Example: a car at 2 going up with a stop at 8, and a down call at 5:
// case 3, turn at 8, cost (8 - 2) + (8 - 5) = 9.
int nearest_car(const Car& car, HallCall call) noexcept {
const Floor here = car.floor();
const int straight = std::abs(call.floor - here);
if (!car.has_stops()) return straight;
const Direction way = car.direction();
const bool ahead = way == Direction::up ? call.floor > here : call.floor < here;
const bool open_here = call.floor == here && car.state() == CarState::doors_open;
if ((ahead || open_here) && call.direction == way) return straight;
Floor turn = car.farthest_stop(way).value_or(here); // no stop ahead: it turns where it is
if (ahead) turn = way == Direction::up ? std::max(turn, call.floor) : std::min(turn, call.floor);
return std::abs(turn - here) + std::abs(turn - call.floor);
}
How this code works: nearest_car on one car, for several calls

These are the values that test AC-4.1 checks. The car started at 2 with a car stop at 8 and took one step, so it is at 3, moving_up, and its farthest stop up is 8.

Call Which case Sum Cost
5 up 2: ahead, and going the car’s way 5 − 3 2
5 down 3: turn at 8, come back to 5 (8 − 3) + (8 − 5) 8
9 down 3: the call is ahead, so the turn is at 9 (9 − 3) + (9 − 9) 6
1 up 3: behind the car; turn at 8, come down to 1 (8 − 3) + (8 − 1) 12
1 down 3: the same route (8 − 3) + (8 − 1) 12

And a car idle at 6 with no stops scores the call 2 up as 6 − 2 = 4: case 1, straight there.

For 1 up, the estimate is right: nothing is below 1, so the car turns at 1 and serves it on arrival, after 12 floors. Whether the estimate is always right is the question in the Exercise.

least_busy scores a car by its number of pending stops and ignores the call entirely (AC-4.5). It spreads work across cars, and it will happily send a car from the far end of the building past a nearer one that has two stops (AC-4.4 shows exactly that). Neither rule is “right”: they trade waiting time against fairness of load, and the point of making the rule a parameter is that the team can compare them on the same random runs.

The curriculum asks for more than one dispatch rule, chosen per building, so the rule must be a parameter. There are three ordinary ways to write that parameter in C++, and the Strategy page covers them in general. Here is the trade-off for this rule.

A plain function pointer (what the code uses). A rule is one question with no memory of its own: given a car and a call, a number. Nothing needs to be built, owned, or destroyed. The building stores one pointer, copying a Building copies it for free, and the type says noexcept.

A Strategy interface would look like this:

IllustrativeA fragment for explanation; not compiled on its own.

// Illustrative: the same choice as a Strategy interface.
class DispatchRule {
public:
virtual ~DispatchRule() = default; // virtual: rules are deleted through a base pointer
[[nodiscard]] virtual int cost(const Car& car, HallCall call) const noexcept = 0;
};
class NearestCar final : public DispatchRule {
public:
[[nodiscard]] int cost(const Car& car, HallCall call) const noexcept override {
return nearest_car(car, call); // the same function, wrapped in a class
}
};

It earns its place when a rule has several operations that belong together (say, cost plus on_call_served to learn from the result), or when rules need to be looked up and configured as objects. The price is a class per rule, and a question the function pointer never asks: who owns the rule object? The building would hold a std::unique_ptr<DispatchRule> (and stop being copyable), or a reference to a rule that someone else owns and that must outlive it.

A std::function can hold a lambda that remembers something:

IllustrativeA fragment for explanation; not compiled on its own.

// Illustrative: a rule with state of its own, which a function pointer cannot hold.
// The lambda keeps its own copy of `weight` (an init-capture). It adds a
// charge for every stop the car already has, to the floors it must travel.
std::function<int(const Car&, HallCall)> rule = [weight = 3](const Car& car, HallCall call) {
return nearest_car(car, call) + weight * car.pending();
};

It earns its place when a rule needs data of its own: a weight to tune, traffic counted over a day, a table loaded from a file. The price is that std::function’s call is not noexcept, so choose_car could no longer promise not to throw (an exception escaping a noexcept function ends the program with std::terminate), and that storing a large lambda may allocate.

None of the rules here has state, so the simplest tool that works is the one the code uses. The comment above CostRule says what would make it change.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

building.hpp
class Building {
public:
// Throws std::invalid_argument for no cars, more than 26 (they are
// named A to Z), no rule, or anything a Car refuses.
explicit Building(BuildingConfig config);
// A hall call: someone on `floor` pressed up or down. Refused for a
// floor that does not exist, or a direction that leads nowhere (up on
// the top floor, down on floor 0). Pressing a lit button again is
// accepted and changes nothing.
Answer hall_call(Floor floor, Direction direction);
// A car call: someone inside car `index` pressed `floor`. Refused for
// a car or a floor that does not exist.
Answer car_call(std::size_t index, Floor floor);
// Advance every car by one step.
void tick();
[[nodiscard]] int now() const noexcept { return now_; }
[[nodiscard]] int floors() const noexcept { return floors_; }
[[nodiscard]] std::size_t car_count() const noexcept { return cars_.size(); }
[[nodiscard]] const Car& car(std::size_t index) const { return cars_.at(index); }
// True when no car has a stop left and every car is idle.
[[nodiscard]] bool settled() const noexcept;
// One trace line: the time and every car, such as "t=3 | A 2 up [5] | B 0 idle []".
[[nodiscard]] std::string describe() const;
private:
[[nodiscard]] std::optional<std::string> floor_problem(Floor floor) const;
[[nodiscard]] std::size_t choose_car(HallCall call) const noexcept;
int floors_;
CostRule rule_;
std::vector<Car> cars_;
int now_ = 0; // ticks so far
};

The building owns the cars, by value, and is the only way in from outside: a caller presses buttons and moves time, and reads cars through const Car&. It never hands out a Car&, so no caller can add a stop behind the building’s checks.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

building.cpp
// Scores every car with the building's rule and takes the lowest. Ties go
// to the car nearer the call, then to the car with the lower index (A
// before B). std::tuple compares element by element, left to right, which
// is exactly that order. Nothing here is random, so the same state always
// gives the same car.
std::size_t Building::choose_car(HallCall call) const noexcept {
std::size_t best = 0;
std::tuple<int, int, std::size_t> best_key{};
for (std::size_t i = 0; i < cars_.size(); ++i) {
const Car& candidate = cars_[i];
const std::tuple<int, int, std::size_t> key{
rule_(candidate, call), std::abs(candidate.floor() - call.floor), i};
if (i == 0 || key < best_key) {
best = i;
best_key = key;
}
}
return best;
}

The tie-break is part of the design, not a detail. Without one, two cars with the same cost would be chosen by whichever the loop met first, and a change to the order of cars would change the behaviour without anyone noticing. With (cost, distance, index), the rule decides first; among equal costs, the nearer car wins; among equal distances too, the lower index wins (AC-4.3). std::tuple’s < compares element by element, left to right, so one comparison says all of that.

How this code works: choose_car on the demo's two hall calls

In the step 1 demo, A is idle at 0 with a car stop at 7, and B is idle at 9 with no stops. Both have the default direction, up. The rule is nearest_car.

Hall call 4 up.

Car nearest_car Key
A has stops; 4 is ahead and up, the car’s way: 4 (4, 4, 0)
B no stops: straight there, 9 − 4 = 5 (5, 5, 1)

A has the smaller key, and takes the call.

Hall call 8 down, now with A holding 4^ and 7.

Car nearest_car Key
A 8 is ahead but down: turn at the larger of 7 and 8, so (8 − 0) + 0 (8, 8, 0)
B no stops: 9 − 8 = 1 (1, 1, 1)

B wins, which is the second complaint answered: the near, free car comes.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

building.cpp
// Checks first, then builds the answer (the only step that can throw,
// because building a string allocates), and changes a car last. If
// anything throws, no car has changed.
Answer Building::hall_call(Floor floor, Direction direction) {
if (std::optional<std::string> problem = floor_problem(floor)) return refused(std::move(*problem));
if (direction == Direction::up && floor == floors_ - 1) {
return refused("There is no up button on the top floor.");
}
if (direction == Direction::down && floor == 0) {
return refused("There is no down button on floor 0.");
}
const HallCall call{floor, direction};
for (std::size_t i = 0; i < cars_.size(); ++i) {
if (cars_[i].has_hall_call(call)) {
return Answer{true, "Already called: car " + cars_[i].name() + " is coming.", i};
}
}
const std::size_t chosen = choose_car(call);
Answer answer{true, "Car " + cars_[chosen].name() + " takes the call.", chosen};
cars_[chosen].add_hall_call(call); // the floor was checked above, so this cannot throw
return answer;
}

The order inside hall_call is the design of NFR-3, the strong guarantee on a small scale:

  1. Every check first. A floor that does not exist, a direction that leads nowhere: refused, and nothing has been touched.
  2. A lit button? If a car already holds this call, say which one, and change nothing (AC-1.6). That is also how INV-5 is kept: a call is never given to a second car.
  3. Choose, which cannot throw (noexcept).
  4. Build the answer. The text is a std::string, and making it may allocate, so it may throw std::bad_alloc. If it does, no car has changed yet.
  5. Change one car. add_hall_call sets a flag. The floor was checked first, so it cannot throw.

The same shape appears in car_call, and again, with more at stake, in step 2’s take_out_of_service.

Rule Where it lives
Which state changes are legal legal_transition, enforced by Car::go
One floor per tick; never move with doors open Car::step
When to stop on arrival Car::wants_to_stop_here
What a stop clears, and when to turn round Car::serve_here
Where to go next Car::next_direction, called by leave_floor, step
How costly a car is for a call the building’s CostRule
Ties between cars Building::choose_car
Which requests are refused Building::hall_call, Building::car_call
When time passes Building::tick, and only there

Take the hall call 8 down in the step 1 demo, from the button to the doors closing.

The demo's hall call 8 down: choosing car B, then three ticks
Text description of the diagram

The person on floor 8 presses down. The building checks the floor and the direction and finds that no car holds 8 down yet. It asks nearest_car for the cost of car A, which is 8, and of car B, which is 1. The key for B, (1, 1, 1), is less than the key for A, (8, 8, 0), so it gives the call to B and answers “Car B takes the call.” On tick 1, A sets off up from 0 and moves to 1, and B, idle at 9 with a stop below, sets off down and moves to 8; on arrival it wants to stop there, opens its doors, and clears the call. On tick 2 its doors count down from 2 to

  1. On tick 3 they reach 0, B has nothing left to do, and it goes idle.
Diagram source (Mermaid)
sequenceDiagram
participant P as person on 8
participant Bd as Building
participant R as nearest_car
participant A as car A
participant B as car B
P->>Bd: hall_call(8, down)
Bd->>Bd: floor and direction ok, no car holds 8v
Bd->>R: cost of A for 8v
R-->>Bd: 8
Bd->>R: cost of B for 8v
R-->>Bd: 1
Bd->>Bd: (1, 1, 1) is less than (8, 8, 0): B
Bd->>B: add_hall_call(8v)
Bd-->>P: Car B takes the call.
Note over Bd: tick 1
Bd->>A: step(): idle, sets off up, moves to 1
Bd->>B: step(): idle, sets off down, moves to 8
B->>B: wants_to_stop_here: yes, open, clear 8v
Note over Bd: tick 2
Bd->>B: step(): doors open, count 2 to 1
Note over Bd: tick 3
Bd->>B: step(): count 1 to 0, nothing to do, idle

Step by step, in the code:

  1. hall_call(8, Direction::down): floor_problem(8) is empty; 8 is not floor 0, so down is allowed; neither car has_hall_call({8, down}).
  2. choose_car builds the keys (8, 8, 0) for A and (1, 1, 1) for B, as in the walkthrough above, and returns 1.
  3. The answer “Car B takes the call.” is built, and only then cars_[1].add_hall_call({8, down}) sets B’s down flag on floor 8.
  4. Tick 1: B’s step is in idle, has a stop, and none on floor 9. next_direction finds nothing up from the top floor and something down, so B faces down, goes to moving_down, and move_one_floor takes it to 8. wants_to_stop_here sees a down call while going down, so open_doors starts the count at 2 and serve_here clears the flag. The demo prints B 8 open [].
  5. Ticks 2 and 3 count the doors down; on 3, leave_floor finds nothing to do and calls go(CarState::idle). The demo prints B 8 idle [].

At no point did a car hold a call that another car held, change state without go, or move with its doors open.

The State pattern, with a class per state, is the other well-known answer. It would fit if each state had a lot of behaviour of its own for many events. Here a car has one event, step, and its four cases fit on one screen; the stops, the floor, and the direction are shared by every state. Splitting step over four classes would hide the order of the rules, which is the thing a reader most needs to see. See Strategy vs State vs Template Method.

The type cannot tell the two rules apart. Both are noexcept, both return an int, and both are cheap. Only a test that sets up a moving car, such as AC-4.1 and AC-4.2, tells them apart.

The dispatch rule is a Strategy in intent: a family of interchangeable ways to answer one question, chosen when the building is made. It is written as a function pointer, not as a class, for the reasons in Why a function pointer. That is the “plain function” option on the Strategy page.

Be clear about what nearest_car is: an estimate. It follows the car’s route to the first turn, then straight to the caller, and that is not always the way the car really goes. Choosing a car by an estimate is normal (real controllers do it with much richer models). The Exercise asks where it goes wrong, and how much it matters.

  • No passengers. The model knows buttons, not people, so there is no capacity, no load, and no “how long has this person waited”. The random tests measure waits from the button press.
  • No Car interface. There is one kind of car. Express cars in step 2 are the same class with a set of floors, not a subclass.
  • No observer or event bus. The demo and the tests read the cars after each tick. Nothing needs to be told.
  • No thread and no clock. Time is tick(), for the reasons above.
  • No exceptions for refused requests. A refusal is an Answer with text. The only exceptions are for programming errors: an illegal transition, a bad config, and (in step 2) a stop given to a car that cannot take it.

The example has two steps, each a complete program with its own tests:

  • Step 1 is the design above: one kind of car, collective control, two dispatch rules, and the building that checks every request.
  • Step 2 is the change: express cars and maintenance mode. See When the requirements change.

The order inside step 1 is worth copying. The state table and go came first, with the test that every illegal move throws (AC-2.4), because every later test trusts that a car cannot do the impossible. Then one car with car stops only, moving one floor a tick and opening for two. Then hall calls and the collective-control rule, one acceptance criterion at a time (AC-3.1 to AC-3.6). Only then the building, with one car and then two, the dispatch rules, and the refusals. The random runs came last, once each rule they check had its own small test.

The demo builds ten floors with car A at 0 and car B at 9, makes two requests that are refused and three that are accepted, and then ticks until the building settles, with one more press in car A at tick 5.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
int main() {
// Floors 0 to 9, doors open for 2 ticks, A starts at 0 and B at 9.
Building building(BuildingConfig{10, 2, {0, 9}, nearest_car});
std::cout << building.describe() << "\n";
say("hall call 12 up", building.hall_call(12, Direction::up));
say("hall call 9 up", building.hall_call(9, Direction::up));
say("in car A, press 7", building.car_call(0, 7));
say("hall call 4 up", building.hall_call(4, Direction::up)); // on A's way up
say("hall call 8 down", building.hall_call(8, Direction::down)); // B is one floor away
// Run until nothing is left to do (with a limit, in case of a bug).
while (!building.settled() && building.now() < 40) {
building.tick();
std::cout << building.describe() << "\n";
if (building.now() == 5) {
// The person who got in at 4 wants floor 2: behind A, so A
// goes on up to 7 first and serves 2 on the way back down.
say("in car A, press 2", building.car_call(0, 2));
}
}
}
Expected output
t=0 | A 0 idle [] | B 9 idle []
hall call 12 up: There is no floor 12 (floors are 0 to 9).
hall call 9 up: There is no up button on the top floor.
in car A, press 7: Car A will stop at 7.
hall call 4 up: Car A takes the call.
hall call 8 down: Car B takes the call.
t=1 | A 1 up [4^ 7] | B 8 open []
t=2 | A 2 up [4^ 7] | B 8 open []
t=3 | A 3 up [4^ 7] | B 8 idle []
t=4 | A 4 open [7] | B 8 idle []
t=5 | A 4 open [7] | B 8 idle []
in car A, press 2: Car A will stop at 2.
t=6 | A 4 up [2 7] | B 8 idle []
t=7 | A 5 up [2 7] | B 8 idle []
t=8 | A 6 up [2 7] | B 8 idle []
t=9 | A 7 open [2] | B 8 idle []
t=10 | A 7 open [2] | B 8 idle []
t=11 | A 7 down [2] | B 8 idle []
t=12 | A 6 down [2] | B 8 idle []
t=13 | A 5 down [2] | B 8 idle []
t=14 | A 4 down [2] | B 8 idle []
t=15 | A 3 down [2] | B 8 idle []
t=16 | A 2 open [] | B 8 idle []
t=17 | A 2 open [] | B 8 idle []
t=18 | A 2 idle [] | B 8 idle []

Read the output against the rules:

  • Floor 12 and up from the top floor are refused before any car is looked at, and t=0 shows that nothing changed.
  • 4 up goes to A, which will pass 4 on its way to 7 (cost 4 against 5). 8 down goes to B, one floor away (cost 1 against 8).
  • B moves one floor, opens at once, keeps its doors open for ticks 1 and 2, and is idle from tick 3.
  • A stops at 4 on the way up, goes on to 7 although 2 was pressed at tick 5, turns at 7, and comes back down for 2. The tick-by-tick reading is in One tick of a car.
  • The building settles at tick 18, with every light off.

The tests are named after the acceptance criteria and run against the real Building and Car. Most build a small building, press buttons, call tick() a set number of times, and check where each car is and what state it is in. No test sleeps.

Beside the small tests, step 1 has three seeded random runs. They share two helpers. The first checks one car across one tick:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step1.cpp
// Checks, for one car, the rules that must hold across every tick. `before`
// is a copy of the car taken just before the tick. Returns a description
// of the first broken rule, or an empty string.
std::string broken_rule(const Car& before, const Car& after) {
const int moved = after.floor() - before.floor();
if (moved < -1 || moved > 1) return "moved more than one floor";
if (moved != 0 && before.state() == CarState::doors_open) return "moved with its doors open";
if (after.state() != before.state() && !legal_transition(before.state(), after.state())) {
return "illegal transition " + to_string(before.state()) + " -> " + to_string(after.state());
}
if (moved != 0) {
// Arriving at a floor that was a stop in the direction of travel
// (a car stop, or a hall call going the same way) must open the doors.
const Direction way = moved > 0 ? Direction::up : Direction::down;
const bool was_a_stop = before.has_car_stop(after.floor()) ||
before.has_hall_call({after.floor(), way});
if (was_a_stop && after.state() != CarState::doors_open) return "skipped a stop";
}
return "";
}

broken_rule compares a copy of the car taken before the tick with the car after it. It checks INV-1 to INV-4 from the outside: one floor at most, no move from doors_open, only legal transitions, and no stop passed with the doors shut. Copying a Car is cheap and allowed, so the test needs no hook inside the class.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step1.cpp
// A seeded random run: for `ticks` ticks, sometimes press a random hall
// button and sometimes a random button in a random car, then tick and
// check every car. Then run on with no new requests until the building
// settles. std::mt19937 gives the same numbers for the same seed on every
// platform; `rng() % n` is used instead of a distribution object because
// distributions may differ between standard libraries.
RunResult random_run(std::uint32_t seed, CostRule rule, int ticks = 600) {
const int floors = 10;
const int door_ticks = 2;
// A generous bound, 180 ticks here. Collective control reaches a stop
// within 2 * (floors - 1) = 18 floors of travel (the page says why), and
// a floor costs at most 1 + 2 * door_ticks = 5 ticks (the move and two
// openings), so the argued worst case is about 90 ticks: twice that.
const int bound = 6 * floors * (door_ticks + 1);
Building building = make(floors, {0, 4, 9}, rule, door_ticks);
std::mt19937 rng(seed);
const auto pick = [&rng](int n) { return static_cast<int>(rng() % static_cast<std::uint32_t>(n)); };
RunResult result;
std::vector<Request> open;
const auto record = [&](bool hall, std::size_t car, HallCall call, const Answer& answer) {
if (!answer.accepted) return;
++result.accepted;
open.push_back(Request{hall, car, call, building.now()});
};
for (int t = 0; t < ticks + 10 * bound; ++t) {
if (t >= ticks && building.settled()) break;
if (t < ticks && pick(10) < 3) {
const HallCall call{pick(floors), pick(2) == 0 ? Direction::up : Direction::down};
record(true, 0, call, building.hall_call(call.floor, call.direction));
}
if (t < ticks && pick(10) < 3) {
const std::size_t car = static_cast<std::size_t>(pick(3));
const Floor floor = pick(floors);
record(false, car, HallCall{floor, Direction::up}, building.car_call(car, floor));
}
std::vector<Car> before;
for (std::size_t i = 0; i < building.car_count(); ++i) before.push_back(building.car(i));
building.tick();
result.trace.push_back(building.describe());
for (std::size_t i = 0; i < building.car_count(); ++i) {
const std::string broken = broken_rule(before[i], building.car(i));
if (!broken.empty()) {
if (result.violations == 0) std::cerr << " t=" << building.now() << ": " << broken << "\n";
++result.violations;
}
}
// Drop the requests that are now served; count the ones too late.
std::vector<Request> still_open;
for (const Request& request : open) {
const int waited = building.now() - request.since;
if (pending(building, request)) {
if (waited > bound) {
++result.late;
} else {
still_open.push_back(request);
}
} else if (waited > result.worst_wait) {
result.worst_wait = waited;
}
}
open = std::move(still_open);
}
result.late += static_cast<int>(open.size()); // never served at all
return result;
}
How this code works: The step 1 random run
  1. A repeatable dice. std::mt19937 rng(seed) is a pseudo-random generator, and the standard fixes its sequence for a given seed, so every platform makes the same presses. pick(n) gives a whole number from 0 to n - 1. It uses rng() % n and not a distribution object, because distributions are allowed to differ between standard libraries.
  2. A busy building. Ten floors, three cars starting at 0, 4, and 9, doors open for 2 ticks. For 600 ticks, each tick has a 3 in 10 chance of a random hall call and a 3 in 10 chance of a random car call. Refused requests (such as up from floor 9) are not counted.
  3. Every car, every tick. Before each tick the test copies the cars; after it, broken_rule checks each one.
  4. Every request, until it is served. Each accepted request is kept with the tick it was made. When its light goes off, its wait is recorded. If it is still lit after bound ticks, it is late.
  5. Then quiet. After tick 600 there are no new requests, and the run goes on until the building settles, or gives up after 10 * bound more ticks and counts what is still lit as late.

The tests use it three ways. AC-5.1 runs seeds 1, 2, and 3 with both rules, and checks that more than 200 requests were accepted (so the run really did something), that none was late, and that the worst wait is above zero. AC-5.2 runs seed 42 twice and checks that the two traces of describe() are equal line for line, and that seed 43 gives a different trace (so the comparison is not trivially true). AC-5.3 runs seeds 7 to 10 with both rules and checks that no invariant was ever broken.

What the bound proves, and what it does not. The bound is 6 × 10 × (2 + 1) = 180 ticks. By the argument in Collective control, a car reaches a stop within 2 × 9 = 18 floors of travel, and a floor costs at most 5 ticks (one to arrive, and two openings of 2 ticks, one each way), so about 90 ticks; 180 is twice that. It is deliberately loose. Passing it shows that, on these seeds, no request was forgotten and no car got stuck going one way, with either rule; those are the failures that matter most. It does not show that waits are short, that one rule beats the other, or that some other seed cannot make a request wait longer. The bound is checked on three seeds per rule; it is evidence, not a proof. To compare the rules, record worst_wait and the average wait for many seeds and look at the numbers, which these tests do not do.

Checking the tests. The code agent that wrote the example reports that 17 hand-written mutations of the step 1 code were tried, one at a time, and that 16 made at least one test fail; it reports the survivor as an equivalent mutant (a change that does not change what the program does). That report was not rerun for this page. The step 2 mutations that were run for it are under Step 2 tests.

“Two things from the building’s owners. Car A is becoming an express: it will stop only at the lobby and the top four floors. And the maintenance team needs to take a car out of service without anyone being left waiting at a lit button.”

Two new rules:

  • FR-6 Express cars. A car may serve only a set of floors. It is never given a hall call on a floor it skips, a car call to such a floor is refused with a reason, and it passes those floors without opening. A hall call on a floor that no car serves is refused.
  • FR-7 Maintenance mode. Taking a car out of service hands its hall calls back at once, and each goes to another car by the usual rule, or waits if no car can take it now. The car finishes its car stops (the people inside still get out), then goes to the maintenance floor and parks there with its doors open, ignoring every call. It can be returned to service only once it is parked; then it takes calls again, starting with the ones that waited.

“Without anyone being left waiting” decides the hardest part. A car’s hall calls are promises to people outside it, and a car leaving service cannot keep them. So the building, which made the promises, must make them again to another car, in the same request that takes the car out.

UC-6 Run an express car.

  • AC-6.1 An express car is never given a call on a floor it skips.
  • AC-6.2 An express car takes calls on its floors.
  • AC-6.3 A car call to a floor the car skips is refused with a reason.
  • AC-6.4 An express car passes the floors it skips without opening.
  • AC-6.5 A hall call on a floor no car serves is refused.
  • AC-6.6 A bad express setup is refused when the building is made: an entry for a car that does not exist, a floor outside the building, an empty list, a car that starts on a floor it skips, or a car that cannot park at the maintenance floor.
  • AC-6.7 The car itself refuses a stop on a floor it skips.

UC-7 Take a car out of service.

  • AC-7.1 Its hall calls are handed back and given to other cars.
  • AC-7.2 Its car stops are finished, then it parks at the maintenance floor, which is configurable.
  • AC-7.3 A car out of service ignores calls.
  • AC-7.4 A call no car can take now waits, and is given out when a car returns.
  • AC-7.5 Handed-back calls wait only when no other car can take them.
  • AC-7.6 Returning to service closes the doors, and the car takes calls again.
  • AC-7.7 Maintenance requests that make no sense are refused: a car that does not exist, a car already out, a car in service returned, or a car returned before it has parked.
  • AC-7.8 A moving car with nothing left ahead stops before it turns.
  • AC-7.9 A car already at the maintenance floor parks at once.
  • AC-7.10 A passenger stop at the maintenance floor is not the end of the trip.
  • AC-7.11 A parked car counts as settled, and a car still on its way to park does not.

AC-7.8 is new because of FR-7. In step 1, a moving car always has a stop ahead, because stops are only added. In step 2, handing calls back can take away every stop ahead of a moving car, and a car cannot reverse in mid-shaft. So it stops (goes idle) for one tick, and sets off the other way on the next, through a transition the table now allows.

File Change
car.hpp/.cpp CarState::out_of_service; five new legal moves; the set of floors served, serves, in_service, hall_calls; take out and return; step parks
building.* express and maintenance_floor in the config; choose_car may find no car; a waiting_ list; take_out_of_service, return_to_service
dispatch.* unchanged
tests the step 1 tests carried over, with AC-2.4 checking the new table; new tests for AC-6 and AC-7; the random run and the invariants extended

The dispatch rules did not change at all, and that is the first thing to notice about where the express rule went.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

building.cpp
// Scores every car that can take the call with the building's rule and
// takes the lowest. Ties go to the car nearer the call, then to the car
// with the lower index (A before B). std::tuple compares element by
// element, left to right, which is exactly that order. Nothing here is
// random, so the same state always gives the same car.
// Step 2: a car can take the call only if it is in service and serves the
// floor; this filter is here, not in the rules, so every rule gets it.
// Empty if no car can take the call now.
std::optional<std::size_t> Building::choose_car(HallCall call) const noexcept {
std::optional<std::size_t> best;
std::tuple<int, int, std::size_t> best_key{};
for (std::size_t i = 0; i < cars_.size(); ++i) {
const Car& candidate = cars_[i];
if (!candidate.in_service() || !candidate.serves(call.floor)) continue;
const std::tuple<int, int, std::size_t> key{
rule_(candidate, call), std::abs(candidate.floor() - call.floor), i};
if (!best || key < best_key) {
best = i;
best_key = key;
}
}
return best;
}

The filter is in choose_car, before the rule is asked. A car that is out of service, or that skips the floor, is never a candidate. That puts the express rule in one place, and every cost rule, the two that exist and any written later, gets it for free. The other place it could go is inside each rule (returning a huge cost for a floor the car skips), which every new rule would have to remember, and which would still let a skipped floor win if every car skipped it.

choose_car now returns std::optional, because “no car can take this call” is a real answer in step 2: every car that serves floor 3 may be out of service.

Refusals come in three layers, each with its own reason:

  1. No car in the building serves the floor: hall_call refuses, “No car stops at floor 3.” (AC-6.5).
  2. A car call to a floor that car skips: car_call refuses, “Car A does not stop at floor 3.” (AC-6.3).
  3. The car itself, if anything else ever tries: check_can_take throws std::invalid_argument (AC-6.7). That is a bug in the building, not a person’s mistake, so it is an exception, not an Answer.

Car::serves with an empty set means “every floor”, so a local car needs no list, and the step 1 tests, which never mention express cars, run unchanged.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

car.hpp
// What a car is doing between two ticks. The doors are open in exactly two
// states, doors_open and out_of_service, so "never move with the doors
// open" is the same as "never change floor in a tick that starts in either".
enum class CarState {
idle, // doors closed and not travelling: waiting, or about to decide
moving_up, // doors closed, travelling up: the next tick moves it one floor up
moving_down, // the same, downwards
doors_open, // stopped at a floor with the doors open for a fixed number of ticks
out_of_service, // step 2: parked at the maintenance floor, doors open, ignoring calls
};
// True if a car may go straight from `from` to `to`. Car::go asks this
// before every change of state, so the table below is the whole state
// machine: any other change is a bug and throws std::logic_error.
// idle -> moving_up, moving_down, doors_open, out_of_service
// moving_* -> doors_open, idle (idle: its stops ahead were handed back)
// doors_open -> idle, moving_up, moving_down, doors_open (open again),
// out_of_service
// out_of_service -> idle (returned to service: the doors close)
// A moving car still cannot reverse without stopping first.
[[nodiscard]] bool legal_transition(CarState from, CarState to) noexcept;

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

car.cpp
void Car::take_out_of_service(Floor parking) {
if (!serves(parking)) throw std::invalid_argument("car " + name_ + " cannot park there");
if (taken_out_) throw std::logic_error("car " + name_ + " is already out of service");
for (Stops& stops : stops_) {
stops.up = false; // handed back: the building gives these to other cars
stops.down = false;
}
taken_out_ = true;
parking_ = parking;
}
void Car::return_to_service() {
if (state_ != CarState::out_of_service) {
throw std::logic_error("car " + name_ + " is not parked");
}
go(CarState::idle); // the doors close
taken_out_ = false;
}

The car’s side of FR-7 is small. take_out_of_service clears the hall call flags (the building has copied them first) and remembers the parking floor; it leaves the car stops alone. return_to_service is allowed only from out_of_service, and goes through go like every other change.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

car.cpp
// One tick. Each state does one thing:
// doors_open count down; at zero, a car taken out that has ended its
// last trip at the parking floor parks (the doors stay
// open); any other car closes its doors and decides what to
// do next (leave_floor)
// idle if anyone is waiting on this floor, open the doors;
// else if there are stops elsewhere, set off and move a floor;
// else, if taken out and at the parking floor, park
// moving_* if nothing is left ahead (step 2), stop here, doors closed;
// else move one floor, and open the doors if it is a stop
// out_of_service nothing: it waits for return_to_service
// The car moves only in idle and moving_*, when its doors are closed.
void Car::step() {
if (state_ == CarState::out_of_service) return;
// Step 2: a car taken out of service whose passengers are all out gets
// one stop, the parking floor. No other stop can be added after that.
const bool last_trip_done = taken_out_ && !has_stops();
if (last_trip_done && floor_ != parking_) stops_at(parking_).car = true;
switch (state_) {
case CarState::doors_open:
--door_ticks_left_;
if (door_ticks_left_ > 0) return; // still open for this tick
if (last_trip_done && floor_ == parking_) {
go(CarState::out_of_service); // the doors stay open
return;
}
leave_floor();
return;
case CarState::idle: {
if (!has_stops()) {
if (last_trip_done && floor_ == parking_) go(CarState::out_of_service); // opens and parks
return;
}
const Stops& here = stops_at(floor_);
if (here.car || here.up || here.down) {
// An idle car has no trip to keep to, so it answers the people
// on its own floor first, turning to face their call if needed.
if (!here.car && !call_flag(here, direction_)) direction_ = opposite(direction_);
open_doors();
return;
}
// There are stops, none of them here, so next_direction has a
// value; value() would throw std::bad_optional_access if not.
direction_ = next_direction().value();
go(moving(direction_));
move_one_floor();
return;
}
case CarState::moving_up:
case CarState::moving_down:
// Step 2: handing back hall calls can leave a moving car with
// nothing ahead. It stops here (doors closed) and decides on the
// next tick, rather than reversing in mid-air or running off the end.
if (!farthest_stop(direction_)) {
go(CarState::idle);
return;
}
move_one_floor();
return;
case CarState::out_of_service:
return; // handled at the top; listed so every state is covered
}
}

Three changes to step, each a few lines:

  • The last trip. A car that has been taken out and has no stops left sets a car stop at the parking floor, so it gets there by the ordinary rules: collective control, one floor a tick, doors on arrival. No second way of moving was written.
  • Parking. When the doors have been open for their ticks at the parking floor and the last trip is done, the car goes to out_of_service and the doors stay open. An idle car already on the parking floor parks at once (AC-7.9). A passenger’s stop at the parking floor, made before the car was taken out, is served first like any other, and only then does the car park (AC-7.10).
  • Nothing ahead. A moving car with no stop left ahead goes idle (AC-7.8), as explained above.
Step 2 adds out of service, and five new moves
Text description of the diagram

Step 2 keeps every move from step 1 and adds five. A moving car, up or down, may go to idle when handing back its hall calls has left nothing ahead of it. A car may go to out of service in two ways: from doors open, when it has been taken out, its last trip is done, and its doors have been open their ticks at the parking floor; or from idle, when it is taken out while idle at the parking floor already. The only way out of out of service is back to idle, when the car is returned to service, and its doors close. There is still no move from moving up to moving down, and none from moving to out of service: a car parks only at a floor, with its doors open.

Diagram source (Mermaid)
stateDiagram-v2
[*] --> idle
idle --> moving_up : stops above
idle --> moving_down : stops below
idle --> doors_open : a stop here
idle --> out_of_service : taken out, already at the parking floor
moving_up --> doors_open : arrived at a stop
moving_down --> doors_open : arrived at a stop
moving_up --> idle : nothing left ahead
moving_down --> idle : nothing left ahead
doors_open --> doors_open : open again
doors_open --> moving_up : stops above
doors_open --> moving_down : stops below
doors_open --> idle : nothing to do
doors_open --> out_of_service : taken out, last trip done, at the parking floor
out_of_service --> idle : returned to service, doors close

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

building.hpp
// Step 2. Takes a car out of service: its hall calls are handed back at
// once and given to other cars by the usual rule (or wait if none can
// take them); its car stops are finished first; then it parks at the
// maintenance floor with its doors open. Refused for a car that does
// not exist or is already out of service.
Answer take_out_of_service(std::size_t index);
// Step 2. Returns a parked car to service and offers it, with the other
// cars, every waiting call, oldest first. Refused for a car that does
// not exist, is in service, or is still on its way to park.
Answer return_to_service(std::size_t index);
// Hall calls accepted while no car that serves their floor was in
// service, oldest first.
[[nodiscard]] const std::vector<HallCall>& waiting() const noexcept { return waiting_; }

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

building.cpp
// Everything that can throw comes first: copying the car's hall calls and
// building the answer both allocate. Only then does any state change, and
// from there on nothing can throw (take_out_of_service clears flags;
// assign_or_wait cannot throw), so a failure leaves every car as it was,
// and success never loses a call half-way.
Answer Building::take_out_of_service(std::size_t index) {
if (index >= cars_.size()) return refused("There is no car " + std::to_string(index) + ".");
Car& target = cars_[index];
if (!target.in_service()) return refused("Car " + target.name() + " is already out of service.");
const std::vector<HallCall> handed_back = target.hall_calls();
Answer answer{true,
"Car " + target.name() + " goes out of service and hands back " +
std::to_string(handed_back.size()) +
(handed_back.size() == 1 ? " hall call." : " hall calls."),
index};
target.take_out_of_service(maintenance_floor_); // the car is now never chosen
for (const HallCall call : handed_back) assign_or_wait(call);
return answer;
}

The order is the same as in hall_call, with more at stake, because this request changes several cars:

  1. Checks. A car that does not exist, or is already out, is refused.
  2. Everything that allocates. hall_calls() copies the car’s calls into a new vector, and the answer’s text is built. Either may throw std::bad_alloc, and if one does, nothing has changed.
  3. The changes, none of which can throw. The car clears its flags. Then each handed-back call goes through assign_or_wait: the best car in service gets it by the usual rule, or it joins waiting_.

Why can assign_or_wait not throw? Choosing is noexcept, setting a flag cannot fail, and waiting_.push_back cannot need memory: the constructor reserved room for 2 * floors calls, one per hall button (an up and a down on every floor), and a call is never in two places, so the list can never outgrow that room. Without the reserve, a push_back in the middle of the loop could throw after some calls had moved and others had not, and the building would be left half-way: some promises kept, the rest lost.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

building.cpp
// Waiting calls are offered again, oldest first. The loop keeps the ones
// still waiting at the front of the vector (`kept` counts them) and then
// cuts the rest off; shrinking a vector never allocates.
Answer Building::return_to_service(std::size_t index) {
if (index >= cars_.size()) return refused("There is no car " + std::to_string(index) + ".");
Car& target = cars_[index];
if (target.in_service()) return refused("Car " + target.name() + " is in service.");
if (target.state() != CarState::out_of_service) {
return refused("Car " + target.name() + " is still on its way to the maintenance floor.");
}
Answer answer{true, "Car " + target.name() + " is back in service.", index};
target.return_to_service();
std::size_t kept = 0;
for (const HallCall call : waiting_) {
if (const std::optional<std::size_t> chosen = choose_car(call)) {
cars_[*chosen].add_hall_call(call);
} else {
waiting_[kept++] = call; // still no car: keep it, in order
}
}
waiting_.resize(kept);
return answer;
}

A car can be returned only once it is parked (AC-7.7). Returning a car still on its way would leave a car in service with a parking stop nobody asked for. After the return, every waiting call is offered again, oldest first, to all cars in service, not only the returned one, by the same choose_car.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

building.cpp
// Checks first, then builds the answer (the only step that can throw,
// because building a string allocates), and changes a car or the waiting
// list last. If anything throws, nothing has changed.
Answer Building::hall_call(Floor floor, Direction direction) {
if (std::optional<std::string> problem = floor_problem(floor)) return refused(std::move(*problem));
if (direction == Direction::up && floor == floors_ - 1) {
return refused("There is no up button on the top floor.");
}
if (direction == Direction::down && floor == 0) {
return refused("There is no down button on floor 0.");
}
bool anyone_serves = false;
for (const Car& each : cars_) anyone_serves = anyone_serves || each.serves(floor);
if (!anyone_serves) return refused("No car stops at floor " + std::to_string(floor) + ".");
const HallCall call{floor, direction};
for (std::size_t i = 0; i < cars_.size(); ++i) {
if (cars_[i].has_hall_call(call)) {
return Answer{true, "Already called: car " + cars_[i].name() + " is coming.", i};
}
}
for (const HallCall& kept : waiting_) {
if (kept.floor == floor && kept.direction == direction) {
return Answer{true, "Already called: waiting for a car.", std::nullopt};
}
}
// The rule for a call no car can take now: the floor is served by some
// car (checked above), so one will come back. Keep the call, rather
// than refuse it and make the person press again later.
const std::optional<std::size_t> chosen = choose_car(call);
Answer answer = chosen ? Answer{true, "Car " + cars_[*chosen].name() + " takes the call.", chosen}
: Answer{true, "No car can come now: the call waits.", std::nullopt};
assign_or_wait(call); // the same choice again; cannot throw (see assign_or_wait)
return answer;
}

hall_call learned two things. A call already waiting is a lit button, and pressing it again says so and changes nothing. And a call no car can take now is accepted: the person was heard, and a car will come when one can. Refusing it would make them press again later, with nobody remembering how long they had waited.

Taking car B out of service at tick 2 of the step 2 demo
Text description of the diagram

Maintenance asks the building to take car B out of service. The building checks that B is in service, then asks B for its hall calls, getting a new vector holding one call, 1 up, and builds the answer text. Only then does it tell B to go out of service with parking floor 0; B clears its hall call flags and remembers the floor. The building then gives the call 1 up to the best car that can take it: A is an express that skips floor 1 and B is out, so only C is asked about, at a cost of 8, and C gets the call. The building answers “Car B goes out of service and hands back 1 hall call.” On tick 3, B has no stops left, so it sets a car stop at 0 and moves to floor 1. On tick 4 it opens at 0. On tick 6, with its doors open their two ticks at the parking floor, it goes out of service.

Diagram source (Mermaid)
sequenceDiagram
participant M as maintenance
participant Bd as Building
participant B as car B
participant R as nearest_car
participant C as car C
M->>Bd: take_out_of_service(B)
Bd->>B: in_service()?
B-->>Bd: yes
Bd->>B: hall_calls()
B-->>Bd: [1 up], a new vector
Bd->>Bd: build the answer text
Bd->>B: take_out_of_service(0)
B->>B: clear hall call flags, remember parking floor 0
Bd->>Bd: assign_or_wait(1 up): A skips 1, B is out
Bd->>R: cost of C for 1 up
R-->>Bd: 8
Bd->>C: add_hall_call(1 up)
Bd-->>M: Car B goes out of service and hands back 1 hall call.
Note over B: tick 3: no stops left, sets a car stop at 0, moves to 1
Note over B: tick 4: opens at 0
Note over B: tick 6: doors done at the parking floor: out of service
How this code works: The step 2 demo, at the ticks that matter

The demo builds ten floors with doors open for 2 ticks. Car A at 0 is an express for floors 0 and 6 to 9; B at 4 and C at 9 serve every floor. The maintenance floor is 0.

When What happens Why
before tick 1 Car call A 3 is refused; car call A 8 is accepted. Hall call 1 up goes to B. A skips 3. For 1 up, A is filtered out (it skips 1); B costs 4 − 1 = 3, C costs 9 − 1 = 8.
after tick 2 B, at 2 going down, is taken out and hands back 1 up, which goes to C. A skips 1 and B is out, so C is the only candidate: idle at 9 with no stops, cost 8.
ticks 3 to 6 B prints leaving: at 1 with a stop at 0, opens at 0 at tick 4, and is out at tick 6. Its last trip is a car stop at the parking floor, set by step; doors open for ticks 4 and 5.
after tick 5 C, at 6 going down for 1 up, is taken out and hands back 1 up, which waits. Hall call 3 down also waits. Car call C 2 is refused. Neither A (skips 1 and 3) nor B or C (out) can take them, but B and C serve those floors, so they are accepted.
after tick 8 Returning C is refused: it is still on its way to the maintenance floor. C is down, not out_of_service.
after tick 12 B is returned. B gets 1 up (cost 1), then 3 down (cost 3). B faces up after turning at 0. For 3 down, with a stop at 1: 3 is ahead but the other way, so the turn is at the larger of 1 and 3.
tick 13 B opens at 1 for 1 up. C, its doors done at 0, is out.
tick 17 B opens at 3, turns down, and clears 3 down. Nothing is above 3, so the call the other way is served here.
tick 19 B is idle. The building is settled, with C still out of service. Parked cars count as settled (AC-7.11), and nothing is waiting.

The step 1 tests are carried over to step 2. Only AC-2.4 changed: it now checks the new moves are allowed (moving to idle, parking, and the return) and that a parked car can go nowhere but idle. That is the evidence that the change did not break FR-1 to FR-5. The new tests follow the use cases, AC-6.1 to AC-7.11, and the seeded random runs are extended.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step2.cpp
// Checks, for one car, the rules that must hold across every tick. `before`
// is a copy of the car taken just before the tick. Returns a description
// of the first broken rule, or an empty string.
std::string broken_rule(const Car& before, const Car& after) {
const int moved = after.floor() - before.floor();
if (moved < -1 || moved > 1) return "moved more than one floor";
const bool doors_were_open = before.state() == CarState::doors_open ||
before.state() == CarState::out_of_service;
if (moved != 0 && doors_were_open) return "moved with its doors open";
if (after.state() != before.state() && !legal_transition(before.state(), after.state())) {
return "illegal transition " + to_string(before.state()) + " -> " + to_string(after.state());
}
if (moved != 0) {
// Arriving at a floor that was a stop in the direction of travel
// (a car stop, or a hall call going the same way) must open the doors.
const Direction way = moved > 0 ? Direction::up : Direction::down;
const bool was_a_stop = before.has_car_stop(after.floor()) ||
before.has_hall_call({after.floor(), way});
if (was_a_stop && after.state() != CarState::doors_open) return "skipped a stop";
}
// Step 2: an express car opens only on its floors; a car out of
// service holds no hall calls; a parked car is at the maintenance floor.
if (after.state() == CarState::doors_open && !after.serves(after.floor())) {
return "opened on a floor it skips";
}
if (!after.in_service() && !after.hall_calls().empty()) return "out of service with hall calls";
if (after.state() == CarState::out_of_service && after.floor() != 0) return "parked off the maintenance floor";
return "";
}

Three new rules are checked on every tick: an express car never opens on a floor it skips, a car out of service holds no hall calls, and a parked car is at the maintenance floor. A car that is out_of_service counts as having its doors open, so it must not move either.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step2.cpp
// A seeded random run: for `ticks` ticks, sometimes press a random hall
// button and sometimes a random button in a random car, then tick and
// check every car. Then run on with no new requests until the building
// settles. std::mt19937 gives the same numbers for the same seed on every
// platform; `rng() % n` is used instead of a distribution object because
// distributions may differ between standard libraries.
// Step 2: car A is an express (floors 0 and 6 to 9), and now and then a
// car is taken out of service or returned. One of the local cars B and C,
// which serve every floor, is always in service, so no call has to wait
// for a car to come back (ac_7 tests the waiting rule on its own).
RunResult random_run(std::uint32_t seed, CostRule rule, int ticks = 600) {
const int floors = 10;
const int door_ticks = 2;
// A generous bound, 180 ticks here. Collective control reaches a stop
// within 2 * (floors - 1) = 18 floors of travel (the page says why), and
// a floor costs at most 1 + 2 * door_ticks = 5 ticks (the move and two
// openings), so the argued worst case is about 90 ticks: twice that.
const int bound = 6 * floors * (door_ticks + 1);
Building building = make(floors, {0, 4, 9}, rule, door_ticks, {{0, {0, 6, 7, 8, 9}}});
std::mt19937 rng(seed);
const auto pick = [&rng](int n) { return static_cast<int>(rng() % static_cast<std::uint32_t>(n)); };
RunResult result;
std::vector<Request> open;
// Prints the first lost request, so a failure says where to look.
const auto lose = [&result, &building](const Request& request) {
if (result.lost == 0) {
std::cerr << " t=" << building.now() << ": lost a request for floor "
<< request.call.floor << "\n";
}
++result.lost;
};
const auto record = [&](bool hall, std::size_t car, HallCall call, const Answer& answer) {
if (!answer.accepted) return;
++result.accepted;
const Request request{hall, car, call, building.now()};
if (pending(building, request)) {
open.push_back(request);
} else if (!served_now(building, request)) { // the open doors serve it at once
lose(request);
}
};
for (int t = 0; t < ticks + 10 * bound; ++t) {
if (t >= ticks && building.settled()) break;
if (t < ticks && pick(10) < 3) {
const HallCall call{pick(floors), pick(2) == 0 ? Direction::up : Direction::down};
record(true, 0, call, building.hall_call(call.floor, call.direction));
}
if (t < ticks && pick(10) < 3) {
const std::size_t car = static_cast<std::size_t>(pick(3));
const Floor floor = pick(floors);
record(false, car, HallCall{floor, Direction::up}, building.car_call(car, floor));
}
if (t < ticks && pick(100) < 3) {
const std::size_t car = static_cast<std::size_t>(pick(3));
const std::size_t other_local = car == 1 ? 2 : 1;
if (building.car(car).in_service()) {
if (car == 0 || building.car(other_local).in_service()) {
// The calls this car hands back start their wait again
// with the car that takes them over.
for (Request& request : open) {
if (request.hall && building.car(car).has_hall_call(request.call)) {
request.since = building.now();
}
}
static_cast<void>(building.take_out_of_service(car));
}
} else {
static_cast<void>(building.return_to_service(car)); // refused if not parked yet
}
}
std::vector<Car> before;
for (std::size_t i = 0; i < building.car_count(); ++i) before.push_back(building.car(i));
building.tick();
result.trace.push_back(building.describe());
for (std::size_t i = 0; i < building.car_count(); ++i) {
const std::string broken = broken_rule(before[i], building.car(i));
if (!broken.empty()) {
if (result.violations == 0) std::cerr << " t=" << building.now() << ": " << broken << "\n";
++result.violations;
}
}
// Drop the requests that are now served; count the ones too late,
// and the ones that went out with no car open for them.
std::vector<Request> still_open;
for (const Request& request : open) {
const int waited = building.now() - request.since;
if (pending(building, request)) {
if (waited > bound) {
++result.late;
} else {
still_open.push_back(request);
}
} else if (!served_now(building, request)) {
lose(request);
} else if (waited > result.worst_wait) {
result.worst_wait = waited;
}
}
open = std::move(still_open);
}
result.late += static_cast<int>(open.size()); // never served at all
return result;
}

The run is the step 1 run with three additions. Car A is an express for 0 and 6 to 9. And each tick has a 3 in 100 chance of picking a car and either taking it out (if it is in service) or returning it (refused if it has not parked yet). One of the two local cars, B and C, is always kept in service, so a call never has to wait for a return; waiting is tested on its own by AC-7.4 and AC-7.5. When a call is handed back, the test resets the start of its wait, because the bound is about how long a car takes once it has the call, and a hand-back starts that again.

The third addition is served_now. In step 1, a light can go off only when a car opens for it. In step 2, taking a car out clears its hall calls, so a light going off is not enough: the run also asks whether a car is open on that floor, facing the call’s way (or, for a car call, whether that car is open there). If not, the request is lost, and AC-5.1 checks that no request was. To check the check, this page’s review ran two mutants of step 2 in a scratch copy, with g++. With the hand-back loop in Building::take_out_of_service deleted, all six AC-5.1 runs reported lost requests (two to five each), as well as AC-7.1, AC-7.5, and AC-7.8 failing; with the lost check removed from the test, the random runs passed with that bug. With a car that parks whenever its doors close at the maintenance floor, even with stops left, AC-7.10 failed, and so did two of the six AC-5.1 runs (one late request each).

The reset of the wait is worth being honest about: it means the random run does not measure the whole wait of a person whose car was taken out. A test that wanted that would need its own, looser bound.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
int main() {
BuildingConfig config;
config.floors = 10;
config.door_ticks = 2;
config.car_starts = {0, 4, 9};
config.express = {{0, {0, 6, 7, 8, 9}}}; // car 0 (A) is the express
config.maintenance_floor = 0;
Building building(config);
std::cout << building.describe() << "\n";
say("in car A, press 3", building.car_call(0, 3));
say("in car A, press 8", building.car_call(0, 8));
say("hall call 1 up", building.hall_call(1, Direction::up)); // A is nearest but skips 1
while (!building.settled() && building.now() < 40) {
building.tick();
std::cout << building.describe() << "\n";
switch (building.now()) {
case 2:
say("take B out of service", building.take_out_of_service(1));
break;
case 5:
say("take C out of service", building.take_out_of_service(2));
say("hall call 3 down", building.hall_call(3, Direction::down));
say("in car C, press 2", building.car_call(2, 2));
break;
case 8:
say("return C to service", building.return_to_service(2)); // still on its way
break;
case 12:
say("return B to service", building.return_to_service(1));
break;
default:
break;
}
}
}
Expected output
t=0 | A 0 idle [] | B 4 idle [] | C 9 idle []
in car A, press 3: Car A does not stop at floor 3.
in car A, press 8: Car A will stop at 8.
hall call 1 up: Car B takes the call.
t=1 | A 1 up [8] | B 3 down [1^] | C 9 idle []
t=2 | A 2 up [8] | B 2 down [1^] | C 9 idle []
take B out of service: Car B goes out of service and hands back 1 hall call.
t=3 | A 3 up [8] | B 1 down leaving [0] | C 8 down [1^]
t=4 | A 4 up [8] | B 0 open leaving [] | C 7 down [1^]
t=5 | A 5 up [8] | B 0 open leaving [] | C 6 down [1^]
take C out of service: Car C goes out of service and hands back 1 hall call.
hall call 3 down: No car can come now: the call waits.
in car C, press 2: Car C is out of service.
t=6 | A 6 up [8] | B 0 out [] | C 5 down leaving [0] | waiting [1^ 3v]
t=7 | A 7 up [8] | B 0 out [] | C 4 down leaving [0] | waiting [1^ 3v]
t=8 | A 8 open [] | B 0 out [] | C 3 down leaving [0] | waiting [1^ 3v]
return C to service: Car C is still on its way to the maintenance floor.
t=9 | A 8 open [] | B 0 out [] | C 2 down leaving [0] | waiting [1^ 3v]
t=10 | A 8 idle [] | B 0 out [] | C 1 down leaving [0] | waiting [1^ 3v]
t=11 | A 8 idle [] | B 0 out [] | C 0 open leaving [] | waiting [1^ 3v]
t=12 | A 8 idle [] | B 0 out [] | C 0 open leaving [] | waiting [1^ 3v]
return B to service: Car B is back in service.
t=13 | A 8 idle [] | B 1 open [3v] | C 0 out []
t=14 | A 8 idle [] | B 1 open [3v] | C 0 out []
t=15 | A 8 idle [] | B 1 up [3v] | C 0 out []
t=16 | A 8 idle [] | B 2 up [3v] | C 0 out []
t=17 | A 8 idle [] | B 3 open [] | C 0 out []
t=18 | A 8 idle [] | B 3 open [] | C 0 out []
t=19 | A 8 idle [] | B 3 idle [] | C 0 out []

Read it with the walkthrough above. Two lines are worth a second look:

  • waiting [1^ 3v] appears from tick 6 to tick 12. Both calls were accepted, and nobody had to press again.
  • B serves both waiting calls in one trip up, because it got them in the same return_to_service and the collective-control rule did the rest.

A plan for 45 minutes, using the time boxes from The design workflow:

Time What to do What to say
About 5 min Ask how many floors and cars, what a person presses, what “serve” means, whether time is real, and what the controller decides. “Am I designing the dispatcher and the car’s logic, or also the motors and the door sensors?”
5 min Sketch Building owning Cars, a car’s stops per floor, its states, and the dispatch rule as a parameter. “One building, one thread, and time is a tick that the caller drives.”
10–15 min Write CarState, the transition table and go, then step and the collective-control rule. State INV-1 to INV-4. “The doors are open in exactly one state, so ‘never move with the doors open’ is one case in one switch.”
10 min Write nearest_car and choose_car with the tie-break; walk one hall call through; show the check-then-answer-then-change order. “The rule is an estimate. It is a parameter so the team can compare rules on the same random runs.”
About 5 min Take a change: express cars, or maintenance. “The filter goes before the rule, so every rule gets it. Handed-back calls are re-promised at once.”

What is usually expected at each level

Level Usually expected
Junior A building, cars, and requests; a direction and a floor per car; stops served in some sensible order, not first-come first-served; a state enum; a few tests of movement.
Mid-level All of the above, plus: collective control stated as a rule; a transition table that refuses illegal moves; discrete time instead of threads; a dispatch rule that follows the car’s route; refusals with reasons; deterministic tests.
Senior All of the above, plus: dispatch as a swappable rule and a reasoned choice of how to write it; a deterministic tie-break; seeded random runs with invariants and an honest bound; changes (express, maintenance) that keep every promise made to a waiting person.

These are this site’s judgement of common practice, as on How to approach a case study, not any company’s rubric.

Questions an interviewer may ask

Why not one thread per car? Real cars move at the same time.

Real cars do, but the decisions do not need to. With one tick that moves every car in a fixed order, the tests are exact and fast, and there is no shared state to lock. A real controller can still call tick() from a timer. If the cars truly needed separate threads (say, separate processors), each car would own its state and receive requests as messages, which is a different design, not this one with locks added. See Thread safety.

How would you show that no request waits for ever?

By argument first: a sweep ends at the farthest stop, which is never beyond the end of the building, so a car turns within a bounded number of ticks, and every stop is served before the car turns a third time, within two sweeps of travel. Then by test: the seeded random runs check every accepted request against a loose bound. The test is evidence on a few seeds, not a proof; the argument is what covers every case.

The rule picks a car, and then a better car becomes free. Do you move the call?

Not in this design: a hall call stays with the car it was given to, which keeps INV-5 simple and makes the answer “Car B takes the call” true. Real controllers often do reassign, which means the lantern a person saw can change. If the requirements asked for it, the place is tick(), after the cars step: ask the rule again for each call not yet being served, and move it only if the gain is large, so calls do not bounce between cars.

Why is choose_car noexcept, and what would break that?

It only reads cars and compares numbers, and the rule’s type says noexcept. That lets hall_call and take_out_of_service choose a car in the part of the code that must not throw. Switching to a std::function rule would break it, because calling a std::function is not noexcept.

How do you add a car that is out of order but not in maintenance?

Ask what “out of order” means first. If it stopped between floors, it cannot finish its car stops or park, so FR-7 does not fit: its hall calls must be handed back, its car stops cannot be served, and the people inside need help, not a dispatch rule. That is a fourth kind of event and probably a new state, with its own row in the table.

  • No passengers, capacity, or load. The model knows buttons. A real car can be full, and a real dispatcher weighs how many people wait and for how long.
  • No real time. A tick is one floor or one door step; real cars accelerate, take different times between floors, and keep the doors open longer for a crowd.
  • No doors or safety systems. There is no door obstruction, no sensor, no overload, no fire service, and no emergency stop. In a real elevator those are separate, certified safety systems, and the dispatcher must never be what keeps people safe.
  • Single process, single thread. Nothing is persisted; a restart forgets every call. The design does not handle concurrent callers; the caller must deliver every request on one thread (NFR-5).
  • The dispatch rules are estimates. nearest_car ignores a second turn and the time spent at stops. See the Exercise.
  • Hall calls are never reassigned. A call stays with its car even when a better one becomes free.
  • No destination dispatch. Many modern buildings ask for the floor in the lobby and group people by destination; this model has up and down buttons only.
  • The random runs measure waits from when a car was given the call. A call handed back in maintenance starts its wait again in the step 2 run.
Requirement Design element Code Tests Status
FR-1 requests hall_call, car_call, floor_problem, Answer step 1 building.* ac_1_1_… to ac_1_7_… Tested
FR-2 one car per hall call choose_car, the tie-break, INV-5 step 1 building.cpp ac_1_1_…, ac_4_2_…, ac_4_3_… Tested
FR-3 movement CarState, step, move_one_floor, door count step 1 car.* ac_2_1_… to ac_2_6_…, random runs Tested
FR-4 collective control wants_to_stop_here, serve_here, next_direction step 1 car.cpp ac_3_1_… to ac_3_6_…, random runs Tested
FR-5 every request served collective control; one owner per call step 1 car.cpp, building.cpp ac_5_1_… Tested on seeds, argued in general
NFR-1 deterministic tick, no clocks or threads step 1 building.cpp ac_5_2_… Tested
NFR-2 no invalid car state legal_transition, go step 1 car.cpp ac_2_4_…, ac_5_3_… Tested
NFR-3 refusals change nothing check, answer, change step 1 building.cpp ac_1_3_… to ac_1_6_…; the out-of-memory case is not Refusals tested; failure part way by reading the code
NFR-4 serving does not allocate Stops per floor, made once step 1 car.hpp, car.cpp none By reading the code
NFR-5 single-threaded documented on Building step 1 building.hpp none: a statement, not a behaviour Stated
FR-6 express cars Car::serves, the filter in choose_car, refusals step 2 car.*, building.cpp ac_6_1_… to ac_6_7_…, step 2 random runs Tested
FR-7 maintenance mode out_of_service, take_out_of_service, waiting_, return_to_service step 2 car.*, building.* ac_7_1_… to ac_7_11_…, step 2 random runs Tested

Exercise: Count the second turn

nearest_car follows a car’s route to its first turn and then goes straight to the caller. Start from step 1.

  1. Find a car and a hall call for which the estimate is too low. By how much, and why?
  2. Write nearest_car_two_turns, with the same CostRule type, that counts the second turn. It must give the same answers as nearest_car for every case in AC-4.1.
  3. Build a building where the new rule chooses a different car from the old one, and show that the call is served sooner.
  4. Which case does your rule still get wrong?
Show the explained answer
  1. A call behind the car, going the car’s way, with a stop beyond it. Car A is at 3 going up, with car stops at 8 and 0, and someone on 1 presses up. nearest_car counts up to 8 and back down to 1: (8 − 3) + (8 − 1) = 12. But going down, the car passes 1 (an up call, the other way) and goes on to 0, its farthest stop down, before it turns again and comes up to 1: 5 + 8 + 1 = 14 floors.

  2. The second turn is at the farthest stop the other way, if it is beyond the call, otherwise at the call itself:

    IllustrativeA fragment for explanation; not compiled on its own.

    // Illustrative: nearest_car, counting a second turn when there is one.
    int nearest_car_two_turns(const Car& car, HallCall call) noexcept {
    const Floor here = car.floor();
    const int straight = std::abs(call.floor - here);
    if (!car.has_stops()) return straight; // idle: straight there
    const Direction way = car.direction();
    const bool ahead = way == Direction::up ? call.floor > here : call.floor < here;
    const bool open_here = call.floor == here && car.state() == CarState::doors_open;
    // On the way, the car's way: it stops there as it passes.
    if ((ahead || open_here) && call.direction == way) return straight;
    // The first turn: the farthest stop ahead, or the call if it is beyond.
    Floor turn = car.farthest_stop(way).value_or(here);
    if (ahead) turn = way == Direction::up ? std::max(turn, call.floor) : std::min(turn, call.floor);
    // A call the other way is served after the first turn.
    if (call.direction != way) return std::abs(turn - here) + std::abs(turn - call.floor);
    // A call the car's way is served after the second turn: at the
    // farthest stop the other way if it is beyond the call, else at the call.
    Floor second = car.farthest_stop(opposite(way)).value_or(call.floor);
    second = way == Direction::up ? std::min(second, call.floor) : std::max(second, call.floor);
    return std::abs(turn - here) + std::abs(turn - second) + std::abs(second - call.floor);
    }

    In the case from answer 1 it gives 5 + 8 + 1 = 14, and with no stop beyond the call (second is the call’s floor) it gives the same as nearest_car.

  3. Twenty floors, car A at 3 going up with stops at 8 and 0, car B idle at 14, and a hall call 1 up. The old rule scores A 12 and B 13, and picks A; the call is served 18 ticks later, after A’s stops at 8 and 0. The new rule scores A 14, and picks B, which comes straight down and serves the call 13 ticks later.

  4. An idle car on the call’s floor that already has stops elsewhere. That can happen for the moment between a request and the next tick. The car will open for the call at once, but neither rule notices, because it is not doors_open, and both score it as if it must first go round. Both rules also ignore the time spent at stops on the way: in this model each stop makes the car door_ticks ticks later (two here) than passing the floor would.

This answer was checked in a scratch program built with GCC against the step 1 library; it is not part of the example in the repository. In that program the new rule gave the same values as nearest_car for every case in AC-4.1, scored the case in answer 1 as 14 against 12, and a simulated run of that car travelled 14 floors and served the call after 18 ticks. The twenty-floor building chose A under the old rule (served after 18 ticks) and B under the new one (served after 13 ticks).

  • Give the car one state, from a short list, and one function that changes it through a table of legal moves. “Never move with the doors open” then becomes a property of one case.
  • Keep stops as flags per floor, made once. Adding, serving, and pressing twice are flag changes, and nothing allocates.
  • Collective control is two small functions: stop for what is ahead in your direction, and turn only when nothing is left ahead. It never passes a stop and never strands one, but it does not promise short waits.
  • Make time a number. A tick() the caller drives gives exact, fast, repeatable tests, and the timer can come later.
  • Make the dispatch rule a parameter, in the simplest form that fits: here a noexcept function pointer. Break ties the same way every time.
  • Check, build the answer, then change. Even a request that moves calls between several cars can be made all-or-nothing, by allocating first and reserving room.
  • A promise made to a waiting person belongs to the building, not the car. When a car leaves service, the building makes it again.