Add elevator module: State-pattern car (idle, moving, doors open, maintenance), LOOK stop rule, round-robin / nearest-car / ETA dispatchers, tick simulation on seeded traffic (8 test classes, 13 transcripts)

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b6W3VPEBweaeA5DE4n
This commit is contained in:
Claude
2026-11-18 21:11:10 +05:30
parent 05f41a3ef7
commit 4180e746ef
48 changed files with 1665 additions and 0 deletions
+1
View File
@@ -27,6 +27,7 @@ One module per article. This repository currently holds:
| [`bookmyshow`](bookmyshow/) | Low-Level Design: BookMyShow Seat Booking in Java (Handling Concurrent Bookings) | this commit | | [`bookmyshow`](bookmyshow/) | Low-Level Design: BookMyShow Seat Booking in Java (Handling Concurrent Bookings) | this commit |
| [`splitwise`](splitwise/) | Low-Level Design: Splitwise (Expense Sharing) in Java | this commit | | [`splitwise`](splitwise/) | Low-Level Design: Splitwise (Expense Sharing) in Java | this commit |
| [`graph-algorithms`](graph-algorithms/) | Graph Algorithms in Java: Dijkstra, Topological Sort and Union-Find | this commit | | [`graph-algorithms`](graph-algorithms/) | Graph Algorithms in Java: Dijkstra, Topological Sort and Union-Find | this commit |
| [`elevator`](elevator/) | Low-Level Design: Elevator System in Java (State Pattern and Scheduling) | this commit |
## `collections` module ## `collections` module
+62
View File
@@ -0,0 +1,62 @@
# elevator
Companion code for the ankurm.com article **Low-Level Design: Elevator System in Java (State Pattern and Scheduling)**.
A tick-based elevator simulation in plain Java: a car built as a State pattern (idle, moving, doors open, maintenance), the LOOK rule that
decides where a car goes next, three dispatchers that choose which car answers a hall button (round robin, nearest car, and one that asks each
car for a forecast of its own future), and a simulation that measures them on seeded traffic. Every figure and console line in the article is
quoted from a file in `output/`, which the JUnit tests write while asserting the same numbers. There is no `docs/` folder: the explanations
live in the article itself.
## Versions
| Component | Version | Verified against |
|---|---|---|
| JDK | Temurin 25.0.5+8 (LTS) | `java -version` |
| JUnit | 6.1.3 | `junit-bom` `maven-metadata.xml` on Maven Central (latest GA) |
| Maven | 3.9.11 | `mvn -version` |
No frameworks and no runtime dependencies: everything in `src/main` is plain Java.
## Quickstart
```bash
cd elevator
export JAVA_HOME=/path/to/jdk-25 PATH="$JAVA_HOME/bin:$PATH"
./scripts/run-all.sh # runs every test and regenerates output/*.txt
```
The first Maven run must be online so the plugins land in the local cache. Every transcript is deterministic: the traffic is generated from
fixed seeds and nothing depends on the wall clock.
## The pieces
| Class | Role |
|---|---|
| `Direction`, `Stop` | UP, DOWN or NONE; a floor a car has promised to visit, tagged with the direction of the button that asked |
| `Car` | floor, heading, stops and riders; delegates every tick to its state; implements the LOOK rule and `eta()` |
| `CarState` | the State interface: `tick(car, lobby)` and `copy()` |
| `IdleState`, `MovingState`, `DoorsOpenState`, `MaintenanceState` | the four behaviours; `DoorsOpenState.open` is where people get off and on |
| `Lobby` | what a car may know about the building; `Lobby.FORECAST` is a do-nothing lobby for cloned cars |
| `Building` | floors, cars, waiting people, a dispatcher; one `tick()` moves the whole world one step |
| `Dispatcher` | chooses the car for a hall button |
| `RoundRobinDispatcher`, `NearestCarDispatcher`, `EtaDispatcher` | the three strategies |
| `Passenger`, `Arrival`, `Traffic`, `Simulation`, `Report` | people, seeded traffic, the run loop and its summary |
| `PolicyComparison`, `StarvationDemo` | FCFS, SSTF and LOOK on a bare list of floors, and the starvation case |
## Transcripts
| File | Written by | What it shows |
|---|---|---|
| `01-single-car-trace.txt` | `TraceTest` | one car, three people, one line per tick; why a DOWN button is skipped while the car goes UP |
| `02-policies.txt`, `02b-starvation.txt` | `PolicyTest` | FCFS vs SSTF vs LOOK distance; SSTF leaving one request waiting 46 ticks |
| `03-dispatchers.txt`, `03b-eta-forecast.txt` | `DispatcherTest` | three dispatchers on 120 people, two traffic shapes; a forecast that matches the real run |
| `04-maintenance.txt`, `04b-all-cars-out.txt` | `MaintenanceTest` | taking a car out of service with a rider aboard; every car out of service |
| `05-capacity.txt` | `CapacityTest` | capacity 2, five people: a full car leaves people behind and the call is re-issued |
| `06-validation.txt`, `06b-stop-outside-shaft.txt` | `ValidationTest` | the exact message for each refused request |
| `07-invariants.txt` | `InvariantsTest` | 900 randomised runs, rules checked after every tick |
| `08-nearest-car-trap.txt`, `08b-same-button.txt` | `PitfallsTest` | the nearest-car trap; five people, one hall call |
## License
MIT &mdash; see [LICENSE](../LICENSE).
+50
View File
@@ -0,0 +1,50 @@
One car, three people, one tick per line (floors 0..9, doors stay open 3 ticks)
===============================================================================
p0 starts at 0 and wants 6 (UP). p1 starts at 4 and wants 8 (UP). p2 starts at 3 and wants 1 (DOWN).
All three press their button at tick 0.
t=00 car0 floor 0 DOORS_OPEN UP stops [4u, 3d, 6] riders [p0(0->6)]
t=01 car0 floor 0 DOORS_OPEN UP stops [4u, 3d, 6] riders [p0(0->6)]
t=02 car0 floor 0 DOORS_OPEN UP stops [4u, 3d, 6] riders [p0(0->6)]
t=03 car0 floor 0 MOVING_UP UP stops [4u, 3d, 6] riders [p0(0->6)]
t=04 car0 floor 1 MOVING_UP UP stops [4u, 3d, 6] riders [p0(0->6)]
t=05 car0 floor 2 MOVING_UP UP stops [4u, 3d, 6] riders [p0(0->6)]
t=06 car0 floor 3 MOVING_UP UP stops [4u, 3d, 6] riders [p0(0->6)]
t=07 car0 floor 4 DOORS_OPEN UP stops [3d, 6, 8] riders [p0(0->6), p1(4->8)]
t=08 car0 floor 4 DOORS_OPEN UP stops [3d, 6, 8] riders [p0(0->6), p1(4->8)]
t=09 car0 floor 4 DOORS_OPEN UP stops [3d, 6, 8] riders [p0(0->6), p1(4->8)]
t=10 car0 floor 4 MOVING_UP UP stops [3d, 6, 8] riders [p0(0->6), p1(4->8)]
t=11 car0 floor 5 MOVING_UP UP stops [3d, 6, 8] riders [p0(0->6), p1(4->8)]
t=12 car0 floor 6 DOORS_OPEN UP stops [3d, 8] riders [p1(4->8)]
t=13 car0 floor 6 DOORS_OPEN UP stops [3d, 8] riders [p1(4->8)]
t=14 car0 floor 6 DOORS_OPEN UP stops [3d, 8] riders [p1(4->8)]
t=15 car0 floor 6 MOVING_UP UP stops [3d, 8] riders [p1(4->8)]
t=16 car0 floor 7 MOVING_UP UP stops [3d, 8] riders [p1(4->8)]
t=17 car0 floor 8 DOORS_OPEN UP stops [3d] riders []
t=18 car0 floor 8 DOORS_OPEN UP stops [3d] riders []
t=19 car0 floor 8 DOORS_OPEN UP stops [3d] riders []
t=20 car0 floor 8 MOVING_DOWN DOWN stops [3d] riders []
t=21 car0 floor 7 MOVING_DOWN DOWN stops [3d] riders []
t=22 car0 floor 6 MOVING_DOWN DOWN stops [3d] riders []
t=23 car0 floor 5 MOVING_DOWN DOWN stops [3d] riders []
t=24 car0 floor 4 MOVING_DOWN DOWN stops [3d] riders []
t=25 car0 floor 3 DOORS_OPEN DOWN stops [1] riders [p2(3->1)]
t=26 car0 floor 3 DOORS_OPEN DOWN stops [1] riders [p2(3->1)]
t=27 car0 floor 3 DOORS_OPEN DOWN stops [1] riders [p2(3->1)]
t=28 car0 floor 3 MOVING_DOWN DOWN stops [1] riders [p2(3->1)]
t=29 car0 floor 2 MOVING_DOWN DOWN stops [1] riders [p2(3->1)]
t=30 car0 floor 1 DOORS_OPEN DOWN stops [] riders []
Door openings (from the building log):
t=0 car0 opens at 0 heading UP off=[] on=[p0(0->6)]
t=7 car0 opens at 4 heading UP off=[] on=[p1(4->8)]
t=12 car0 opens at 6 heading UP off=[p0(0->6)] on=[]
t=17 car0 opens at 8 heading UP off=[p1(4->8)] on=[]
t=25 car0 opens at 3 heading DOWN off=[] on=[p2(3->1)]
t=30 car0 opens at 1 heading DOWN off=[p2(3->1)] on=[]
Per person (ticks): wait = button to boarding, ride = boarding to arrival
p0 p0(0->6) wait 0 ride 12 total 12
p1 p1(4->8) wait 7 ride 10 total 17
p2 p2(3->1) wait 25 ride 5 total 30
+8
View File
@@ -0,0 +1,8 @@
One car at floor 5 heading up, six requests: floors travelled
=============================================================
requests in arrival order: [8, 2, 9, 1, 6, 3]
FCFS order [8, 2, 9, 1, 6, 3] distance 32
SSTF order [6, 8, 9, 3, 2, 1] distance 12
LOOK order [6, 8, 9, 3, 2, 1] distance 12
+7
View File
@@ -0,0 +1,7 @@
A request waits at floor 0; the car is at floor 5; new requests keep appearing at floors 6 and 7
================================================================================================
The stream of new requests lasts 40 ticks. The car moves one floor per tick.
SSTF far request served at tick 46
LOOK far request served at tick 9
+20
View File
@@ -0,0 +1,20 @@
12 floors, 3 cars (capacity 8), 120 people: same seeded traffic through three dispatchers
=========================================================================================
Times are in ticks. 'wait' is button press to boarding; 'total' is button press to arrival.
Up-peak (70% start at the lobby), seed 42, arrivals spread over 240 ticks
round-robin delivered 120/120 wait avg 18.5 max 57 total avg 32.7 max 79 floors 363 door cycles 134 ticks 299
hall calls per car (car0, car1, car2): [15, 15, 15]
nearest-car delivered 120/120 wait avg 91.9 max 248 total avg 106.4 max 258 floors 317 door cycles 129 ticks 481
hall calls per car (car0, car1, car2): [23, 15, 4]
eta delivered 120/120 wait avg 13.7 max 43 total avg 27.6 max 63 floors 338 door cycles 136 ticks 273
hall calls per car (car0, car1, car2): [18, 15, 14]
Between floors (uniform origin and destination), seed 7, arrivals spread over 360 ticks
round-robin delivered 120/120 wait avg 13.3 max 45 total avg 22.6 max 69 floors 564 door cycles 181 ticks 400
hall calls per car (car0, car1, car2): [30, 30, 29]
nearest-car delivered 120/120 wait avg 16.5 max 66 total avg 26.5 max 86 floors 428 door cycles 177 ticks 398
hall calls per car (car0, car1, car2): [36, 25, 26]
eta delivered 120/120 wait avg 9.9 max 43 total avg 19.6 max 61 floors 489 door cycles 190 ticks 378
hall calls per car (car0, car1, car2): [37, 28, 33]
+5
View File
@@ -0,0 +1,5 @@
ETA forecast for an idle car at floor 0 and a call at floor 7 (UP)
==================================================================
predicted: 7 ticks
actual: 7 ticks
+18
View File
@@ -0,0 +1,18 @@
Taking car0 out of service while it carries a passenger
=======================================================
t=5: maintenance requested for car0, which is carrying 'a' to floor 5
t=05 car0 floor 2 MOVING_UP UP stops [5] riders [a(0->5)] | car1 floor 8 MOVING_DOWN DOWN stops [2u] riders []
t=06 car0 floor 3 MOVING_UP UP stops [5] riders [a(0->5)] | car1 floor 7 MOVING_DOWN DOWN stops [2u] riders []
t=07 car0 floor 4 MOVING_UP UP stops [5] riders [a(0->5)] | car1 floor 6 MOVING_DOWN DOWN stops [2u] riders []
t=08 car0 floor 5 DOORS_OPEN UP stops [] riders [] | car1 floor 5 MOVING_DOWN DOWN stops [2u] riders []
t=09 car0 floor 5 DOORS_OPEN UP stops [] riders [] | car1 floor 4 MOVING_DOWN DOWN stops [2u] riders []
t=10 car0 floor 5 DOORS_OPEN UP stops [] riders [] | car1 floor 3 MOVING_DOWN DOWN stops [2u] riders []
t=11 car0 floor 5 IDLE NONE stops [] riders [] | car1 floor 2 DOORS_OPEN UP stops [6] riders [b(2->6)]
t=12 car0 floor 5 MAINTENANCE NONE stops [] riders [] | car1 floor 2 DOORS_OPEN UP stops [6] riders [b(2->6)]
car0 entered MAINTENANCE at tick 12 at floor 5
hall call for 'b' went to: t=5 hall 2u -> car1 (at 9 IDLE)
after returnToService(): car0 floor 5 DOORS_OPEN UP stops [9] riders [c(5->9)]
+5
View File
@@ -0,0 +1,5 @@
Both cars out of service, one person presses a button
=====================================================
after 10 ticks: delivered=0 waiting=1
car1 returned to service: delivered after 11 more ticks
+22
View File
@@ -0,0 +1,22 @@
Capacity 2, five people at the lobby, all going UP
==================================================
hall calls dispatched after five button presses: 1
t=0 hall 0u -> car0 (at 0 IDLE)
t=0 hall 0u -> car0 (at 0 DOORS_OPEN)
t=0 car0 opens at 0 heading UP off=[] on=[p0(0->2), p1(0->3)]
t=5 car0 opens at 2 heading UP off=[p0(0->2)] on=[]
t=9 car0 opens at 3 heading UP off=[p1(0->3)] on=[]
t=15 hall 0u -> car0 (at 0 DOORS_OPEN)
t=15 car0 opens at 0 heading UP off=[] on=[p2(0->4), p3(0->5)]
t=22 car0 opens at 4 heading UP off=[p2(0->4)] on=[]
t=26 car0 opens at 5 heading UP off=[p3(0->5)] on=[]
t=34 car0 opens at 0 heading UP off=[] on=[p4(0->6)]
t=43 car0 opens at 6 heading UP off=[p4(0->6)] on=[]
p0(0->2) wait 0 ride 5
p1(0->3) wait 0 ride 9
p2(0->4) wait 15 ride 7
p3(0->5) wait 15 ride 11
p4(0->6) wait 34 ride 9
+10
View File
@@ -0,0 +1,10 @@
Requests the building refuses, and the exact message
====================================================
origin above the top floor -> origin floor 12 is outside 0..9
origin below the ground floor -> origin floor -1 is outside 0..9
destination above the top floor -> destination floor 10 is outside 0..9
destination below the ground floor -> destination floor -4 is outside 0..9
same origin and destination -> origin and destination are both floor 5
people waiting afterwards: 0, hall calls dispatched: 0
@@ -0,0 +1,4 @@
A stop above the top floor
==========================
addStop(10) -> floor 10 is outside 0..9
+7
View File
@@ -0,0 +1,7 @@
Randomised runs: 150 seeds x 3 dispatchers x 2 traffic shapes, rules checked after every tick
=============================================================================================
runs: 900
people delivered: 36000
simulated ticks checked: 137430
rule violations: 0
+11
View File
@@ -0,0 +1,11 @@
Hall call UP at floor 3 while car0 (at 4) is going DOWN and car1 waits at 9
===========================================================================
nearest-car: after 4 ticks car0 floor 4 MOVING_DOWN DOWN stops [0] riders [rider(4->0)]
nearest-car: t=4 hall 3u -> car0 (at 4 MOVING_DOWN)
eta: after 4 ticks car0 floor 4 MOVING_DOWN DOWN stops [0] riders [rider(4->0)]
eta: t=4 hall 3u -> car1 (at 9 IDLE)
wait for the person at floor 3, in ticks:
nearest-car 9
eta 5
+5
View File
@@ -0,0 +1,5 @@
Five people at floor 6 all press UP
===================================
hall calls dispatched: 1
door cycles used to serve all five: 2
+64
View File
@@ -0,0 +1,64 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ankurm.interviewlab</groupId>
<artifactId>elevator</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>
<name>java-interview-lab :: elevator</name>
<description>
Runnable companion code for ankurm.com's "Low-Level Design: Elevator System in Java" article: State pattern car, LOOK scheduling,
three dispatchers (nearest, round robin, ETA) and a tick-based simulation.
</description>
<properties>
<maven.compiler.release>25</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<junit.version>6.1.3</junit.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.junit</groupId>
<artifactId>junit-bom</artifactId>
<version>${junit.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-launcher</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.14.0</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.6.0</version>
<configuration>
<argLine>-Xmx512m -Duser.timezone=UTC -Dfile.encoding=UTF-8</argLine>
</configuration>
</plugin>
</plugins>
</build>
</project>
+9
View File
@@ -0,0 +1,9 @@
#!/usr/bin/env bash
# Regenerates every file in output/. Needs JDK 25 and Maven. The first Maven run must be online.
# Every file is written by a JUnit test that asserts the same numbers it prints, so the figures
# in the article are assertions: they fail the build the moment they stop being true.
set -euo pipefail
cd "$(dirname "$0")/.."
rm -rf output && mkdir -p output
mvn -B -q -T1 test
echo "done:"; ls -1 output
@@ -0,0 +1,4 @@
package com.ankurm.interviewlab.elevator;
/** A person who will walk up to a lift at a given tick. */
public record Arrival(long tick, int origin, int destination) { }
@@ -0,0 +1,118 @@
package com.ankurm.interviewlab.elevator;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
/** Floors 0..floors-1, some cars, one dispatcher, and the people waiting in the lobbies. */
public final class Building implements Lobby {
private final int floors;
private final List<Car> cars = new ArrayList<>();
private final Dispatcher dispatcher;
private final Map<Integer, Deque<Passenger>> waiting = new TreeMap<>();
private final List<Passenger> delivered = new ArrayList<>();
private final List<Stop> unassigned = new ArrayList<>();
private final List<String> log = new ArrayList<>();
private long now;
private int hallCallsDispatched;
public Building(int floors, int[] startFloors, int capacity, Dispatcher dispatcher) {
this.floors = floors;
this.dispatcher = dispatcher;
for (int i = 0; i < startFloors.length; i++) {
cars.add(new Car(i, 0, floors - 1, startFloors[i], capacity));
}
}
/** Cars start spread evenly over the shaft, the way a parking policy would leave them. */
public static Building of(int floors, int carCount, int capacity, Dispatcher dispatcher) {
int[] start = new int[carCount];
for (int i = 0; i < carCount; i++) start[i] = carCount == 1 ? 0 : i * (floors - 1) / (carCount - 1);
return new Building(floors, start, capacity, dispatcher);
}
public List<Car> cars() { return Collections.unmodifiableList(cars); }
public List<Passenger> deliveredPassengers() { return Collections.unmodifiableList(delivered); }
public List<String> log() { return Collections.unmodifiableList(log); }
public int hallCallsDispatched() { return hallCallsDispatched; }
public int floors() { return floors; }
public int waitingCount() { return waiting.values().stream().mapToInt(Deque::size).sum(); }
public Dispatcher dispatcher() { return dispatcher; }
/** A person walks up to the lift and presses the button for their direction. */
public void submit(Passenger p) {
if (p.origin() < 0 || p.origin() >= floors) {
throw new IllegalArgumentException("origin floor " + p.origin() + " is outside 0.." + (floors - 1));
}
if (p.destination() < 0 || p.destination() >= floors) {
throw new IllegalArgumentException("destination floor " + p.destination() + " is outside 0.." + (floors - 1));
}
if (p.origin() == p.destination()) {
throw new IllegalArgumentException("origin and destination are both floor " + p.origin());
}
waiting.computeIfAbsent(p.origin(), f -> new ArrayDeque<>()).add(p);
if (!hallStopPending(p.origin(), p.direction())) callHall(p.origin(), p.direction());
}
/** One tick of the whole building: retry unassigned calls, then every car acts once. */
public void tick() {
if (!unassigned.isEmpty()) {
List<Stop> retry = new ArrayList<>(unassigned);
unassigned.clear();
for (Stop s : retry) callHall(s.floor(), s.dir());
}
for (Car c : cars) c.tick(this);
now++;
}
// ---- Lobby -----------------------------------------------------------------------------
@Override public long now() { return now; }
@Override
public Deque<Passenger> waitingAt(int floor) {
return waiting.computeIfAbsent(floor, f -> new ArrayDeque<>());
}
@Override
public boolean hallStopPending(int floor, Direction dir) {
Stop wanted = new Stop(floor, dir);
return unassigned.contains(wanted) || cars.stream().anyMatch(c -> c.stops().contains(wanted));
}
@Override
public void callHall(int floor, Direction dir) {
List<Car> available = cars.stream().filter(Car::accepting).toList();
Stop stop = new Stop(floor, dir);
if (available.isEmpty()) {
if (!unassigned.contains(stop)) unassigned.add(stop);
return;
}
Car chosen = dispatcher.choose(available, floor, dir);
chosen.addStop(stop);
hallCallsDispatched++;
log.add("t=" + now + " hall " + stop + " -> car" + chosen.id() + " (at " + chosen.floor() + " " + chosen.stateName() + ")");
}
@Override
public void hallServed(Car by, int floor, Direction dir) {
Stop stop = new Stop(floor, dir);
for (Car c : cars) {
if (c != by) c.removeStops(java.util.Set.of(stop));
}
}
@Override public void boarded(Passenger p) { p.boardedAt(now); }
@Override
public void delivered(Passenger p) {
p.arrivedAt(now);
delivered.add(p);
}
@Override public void log(String message) { log.add(message); }
}
@@ -0,0 +1,174 @@
package com.ankurm.interviewlab.elevator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
/**
* One elevator car. It holds the data (floor, heading, promised stops, riders) and delegates
* every tick to its current {@link CarState}.
*/
public final class Car {
/** Ticks the doors stay open. */
public static final int DWELL_TICKS = 3;
private final int id;
private final int minFloor;
private final int maxFloor;
private final int capacity;
private int floor;
private Direction heading = Direction.NONE;
private CarState state = new IdleState();
private final Set<Stop> stops = new LinkedHashSet<>();
private final List<Passenger> riders = new ArrayList<>();
private boolean maintenanceRequested;
private int floorsTravelled;
private int doorCycles;
public Car(int id, int minFloor, int maxFloor, int startFloor, int capacity) {
this.id = id;
this.minFloor = minFloor;
this.maxFloor = maxFloor;
this.floor = startFloor;
this.capacity = capacity;
}
// ---- read side -------------------------------------------------------------------------
public int id() { return id; }
public int floor() { return floor; }
public Direction heading() { return heading; }
public String stateName() { return state.name(); }
public int capacity() { return capacity; }
public int riderCount() { return riders.size(); }
public List<Passenger> riders() { return Collections.unmodifiableList(riders); }
public Set<Stop> stops() { return Collections.unmodifiableSet(stops); }
public int floorsTravelled() { return floorsTravelled; }
public int doorCycles() { return doorCycles; }
public boolean maintenanceRequested() { return maintenanceRequested; }
public boolean inMaintenance() { return state instanceof MaintenanceState; }
/** May the dispatcher give this car new work? */
public boolean accepting() { return !maintenanceRequested && !inMaintenance(); }
// ---- commands --------------------------------------------------------------------------
public void addStop(Stop stop) {
if (stop.floor() < minFloor || stop.floor() > maxFloor) {
throw new IllegalArgumentException("floor " + stop.floor() + " is outside " + minFloor + ".." + maxFloor);
}
if (stop.dir() == Direction.NONE && stop.floor() == floor) return; // already here
stops.add(stop);
}
public void requestMaintenance() { maintenanceRequested = true; }
public void returnToService() {
maintenanceRequested = false;
if (state instanceof MaintenanceState) state = new IdleState();
}
void tick(Lobby lobby) { state.tick(this, lobby); }
// ---- the LOOK rule ---------------------------------------------------------------------
/** Is there a stop strictly ahead of the car when travelling in direction h? */
boolean aheadOf(Direction h) {
for (Stop s : stops) {
if ((h == Direction.UP && s.floor() > floor) || (h == Direction.DOWN && s.floor() < floor)) return true;
}
return false;
}
Set<Stop> stopsHere() {
Set<Stop> here = new LinkedHashSet<>();
for (Stop s : stops) {
if (s.floor() == floor) here.add(s);
}
return here;
}
/**
* The stops at this floor that a car travelling in direction h should serve now: stops going
* the same way, car calls, and (only at the turning point) stops going the other way.
*/
Set<Stop> servedHere(Direction h) {
Set<Stop> here = stopsHere();
Set<Stop> served = new LinkedHashSet<>();
for (Stop s : here) {
if (s.dir() == h || s.dir() == Direction.NONE) served.add(s);
}
boolean sameDirectionHall = served.stream().anyMatch(s -> s.dir() == h);
if (!aheadOf(h) && !sameDirectionHall) {
for (Stop s : here) {
if (s.dir() == h.opposite()) served.add(s);
}
}
return served;
}
/** Keep going while there is something ahead, turn round when there is only something behind, else stop. */
Direction nextHeading() {
if (heading != Direction.NONE) {
if (aheadOf(heading)) return heading;
if (aheadOf(heading.opposite())) return heading.opposite();
return Direction.NONE;
}
int best = Integer.MAX_VALUE;
Direction dir = Direction.NONE;
for (Stop s : stops) {
if (s.floor() == floor) continue;
int d = Math.abs(s.floor() - floor);
Direction towards = Direction.between(floor, s.floor());
if (d < best || (d == best && towards == Direction.UP)) {
best = d;
dir = towards;
}
}
return dir;
}
// ---- forecasting -----------------------------------------------------------------------
/**
* Ticks until this car would open its doors for a new hall call, found by cloning the car
* and running the real state machine forward. Nobody boards in the clone, so the figure
* ignores stops the car will pick up on the way: an estimate, not a promise.
*/
public int eta(int callFloor, Direction callDir) {
Car copy = new Car(id, minFloor, maxFloor, floor, capacity);
copy.heading = heading;
copy.state = state.copy();
copy.stops.addAll(stops);
copy.riders.addAll(riders);
Stop wanted = new Stop(callFloor, callDir);
copy.stops.add(wanted);
for (int t = 1; t <= 1000; t++) {
copy.tick(Lobby.FORECAST);
if (!copy.stops.contains(wanted)) return t;
}
return Integer.MAX_VALUE;
}
// ---- package-private mutators used by the states ----------------------------------------
void setState(CarState next) { this.state = next; }
CarState state() { return state; }
void setHeading(Direction h) { this.heading = h; }
void removeStops(Set<Stop> served) { stops.removeAll(served); }
List<Passenger> ridersMutable() { return riders; }
void countDoorCycle() { doorCycles++; }
void step(Direction d) {
floor += d.delta();
floorsTravelled++;
if (floor < minFloor || floor > maxFloor) throw new IllegalStateException("car" + id + " left the shaft at " + floor);
}
@Override
public String toString() {
return "car" + id + "@" + floor + " " + state.name() + " stops=" + stops;
}
}
@@ -0,0 +1,11 @@
package com.ankurm.interviewlab.elevator;
/** One behaviour of a car. The car owns the data; each state owns what happens on a tick. */
interface CarState {
String name();
void tick(Car car, Lobby lobby);
/** A copy with the same internal counters, so a cloned car can be run forward without touching the real one. */
CarState copy();
}
@@ -0,0 +1,26 @@
package com.ankurm.interviewlab.elevator;
/** Travel direction of a car, or of a hall button. NONE means "either": a car call, or an idle car. */
public enum Direction {
UP, DOWN, NONE;
public Direction opposite() {
return switch (this) {
case UP -> DOWN;
case DOWN -> UP;
case NONE -> NONE;
};
}
public int delta() {
return switch (this) {
case UP -> 1;
case DOWN -> -1;
case NONE -> 0;
};
}
public static Direction between(int from, int to) {
return Integer.compare(to, from) > 0 ? UP : Integer.compare(to, from) < 0 ? DOWN : NONE;
}
}
@@ -0,0 +1,10 @@
package com.ankurm.interviewlab.elevator;
import java.util.List;
/** Chooses which car answers a hall button. Only cars that are accepting work are passed in. */
public interface Dispatcher {
String name();
Car choose(List<Car> candidates, int floor, Direction dir);
}
@@ -0,0 +1,82 @@
package com.ankurm.interviewlab.elevator;
import java.util.ArrayList;
import java.util.Deque;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
/** Doors open for a fixed number of ticks: people get off, people get on, then the car decides where to go. */
final class DoorsOpenState implements CarState {
private int remaining;
DoorsOpenState(int remaining) { this.remaining = remaining; }
/** Everything that happens the moment the doors open at the car's current floor. */
static void open(Car car, Lobby lobby, Set<Stop> served) {
int floor = car.floor();
car.removeStops(served);
final Direction before = car.heading();
Direction h = before;
Direction firstHall = served.stream().map(Stop::dir).filter(d -> d != Direction.NONE).findFirst().orElse(Direction.NONE);
boolean servesHeading = served.stream().anyMatch(s -> s.dir() != Direction.NONE && s.dir() == before);
if (h == Direction.NONE) {
h = firstHall;
} else if (!servesHeading && firstHall != Direction.NONE) {
h = h.opposite(); // turning point: nothing further ahead, so the car reverses here
}
car.setHeading(h);
for (Stop s : served) {
if (s.dir() != Direction.NONE) lobby.hallServed(car, floor, s.dir());
}
car.countDoorCycle();
// Switch state before anything below can ask the dispatcher for a forecast of this car:
// a clone taken while the car still says MOVING would drive off the end of the shaft.
car.setState(new DoorsOpenState(Car.DWELL_TICKS));
List<Passenger> off = new ArrayList<>();
for (Iterator<Passenger> it = car.ridersMutable().iterator(); it.hasNext(); ) {
Passenger p = it.next();
if (p.destination() == floor) {
it.remove();
off.add(p);
lobby.delivered(p);
}
}
List<Passenger> on = new ArrayList<>();
Deque<Passenger> queue = lobby.waitingAt(floor);
for (Iterator<Passenger> it = queue.iterator(); it.hasNext(); ) {
Passenger p = it.next();
if (p.direction() == h && car.riderCount() < car.capacity()) {
it.remove();
car.ridersMutable().add(p);
lobby.boarded(p);
car.addStop(new Stop(p.destination(), Direction.NONE));
on.add(p);
}
}
for (Direction d : new Direction[] {Direction.UP, Direction.DOWN}) {
boolean left = queue.stream().anyMatch(p -> p.direction() == d);
if (left && !lobby.hallStopPending(floor, d)) lobby.callHall(floor, d);
}
lobby.log("t=" + lobby.now() + " car" + car.id() + " opens at " + floor + " heading " + h
+ " off=" + off + " on=" + on);
}
@Override public String name() { return "DOORS_OPEN"; }
@Override
public void tick(Car car, Lobby lobby) {
if (--remaining > 0) return;
Direction next = car.nextHeading();
car.setHeading(next);
car.setState(next == Direction.NONE ? new IdleState() : new MovingState(next));
}
@Override public CarState copy() { return new DoorsOpenState(remaining); }
}
@@ -0,0 +1,18 @@
package com.ankurm.interviewlab.elevator;
import java.util.Comparator;
import java.util.List;
/** Asks every car "how long until you would open your doors there?" and picks the smallest answer. */
public final class EtaDispatcher implements Dispatcher {
@Override public String name() { return "eta"; }
@Override
public Car choose(List<Car> candidates, int floor, Direction dir) {
return candidates.stream()
.min(Comparator.comparingInt((Car c) -> c.eta(floor, dir))
.thenComparingInt(c -> c.stops().size())
.thenComparingInt(Car::id))
.orElseThrow();
}
}
@@ -0,0 +1,38 @@
package com.ankurm.interviewlab.elevator;
import java.util.LinkedHashSet;
import java.util.Set;
/** Doors closed, nothing to do until a stop appears. */
final class IdleState implements CarState {
@Override public String name() { return "IDLE"; }
@Override
public void tick(Car car, Lobby lobby) {
if (car.maintenanceRequested() && car.riderCount() == 0 && car.stops().isEmpty()) {
car.setHeading(Direction.NONE);
car.setState(new MaintenanceState());
lobby.log("car" + car.id() + " out of service at floor " + car.floor());
return;
}
Set<Stop> here = car.stopsHere();
if (!here.isEmpty()) {
Direction first = here.stream().map(Stop::dir).filter(d -> d != Direction.NONE).findFirst().orElse(Direction.NONE);
Set<Stop> served = new LinkedHashSet<>();
for (Stop s : here) {
if (s.dir() == first) served.add(s);
}
car.setHeading(Direction.NONE);
DoorsOpenState.open(car, lobby, served);
return;
}
Direction next = car.nextHeading();
if (next != Direction.NONE) {
car.setHeading(next);
car.setState(new MovingState(next));
car.state().tick(car, lobby);
}
}
@Override public CarState copy() { return new IdleState(); }
}
@@ -0,0 +1,43 @@
package com.ankurm.interviewlab.elevator;
import java.util.ArrayDeque;
import java.util.Deque;
/**
* What a car is allowed to know about the building around it. The real implementation is
* {@link Building}; {@link #FORECAST} is a do-nothing lobby used when a car is cloned to predict
* its own future (see {@link Car#eta}).
*/
interface Lobby {
long now();
/** People waiting at a floor, oldest first. The deque is live: boarding removes from it. */
Deque<Passenger> waitingAt(int floor);
/** Does any car already hold a stop for this hall button? */
boolean hallStopPending(int floor, Direction dir);
/** A hall button needs a car: hand it to the dispatcher. */
void callHall(int floor, Direction dir);
/** A car has opened its doors for this hall button: every other car drops the same stop. */
void hallServed(Car by, int floor, Direction dir);
void boarded(Passenger p);
void delivered(Passenger p);
void log(String message);
Lobby FORECAST = new Lobby() {
private final Deque<Passenger> nobody = new ArrayDeque<>();
public long now() { return 0; }
public Deque<Passenger> waitingAt(int floor) { return nobody; }
public boolean hallStopPending(int floor, Direction dir) { return true; }
public void callHall(int floor, Direction dir) { }
public void hallServed(Car by, int floor, Direction dir) { }
public void boarded(Passenger p) { }
public void delivered(Passenger p) { }
public void log(String message) { }
};
}
@@ -0,0 +1,8 @@
package com.ankurm.interviewlab.elevator;
/** Out of service. Adding this state touched no other state class: only IdleState decides to enter it. */
final class MaintenanceState implements CarState {
@Override public String name() { return "MAINTENANCE"; }
@Override public void tick(Car car, Lobby lobby) { }
@Override public CarState copy() { return new MaintenanceState(); }
}
@@ -0,0 +1,23 @@
package com.ankurm.interviewlab.elevator;
import java.util.Set;
/** Travelling one floor per tick. Opens the doors when the floor it reaches is one it must serve. */
final class MovingState implements CarState {
private final Direction direction;
MovingState(Direction direction) { this.direction = direction; }
@Override public String name() { return "MOVING_" + direction; }
@Override
public void tick(Car car, Lobby lobby) {
car.step(direction);
Set<Stop> served = car.servedHere(direction);
if (!served.isEmpty()) {
DoorsOpenState.open(car, lobby, served);
}
}
@Override public CarState copy() { return new MovingState(direction); }
}
@@ -0,0 +1,16 @@
package com.ankurm.interviewlab.elevator;
import java.util.Comparator;
import java.util.List;
/** The obvious first idea: the car with the smallest floor distance. It ignores which way the car is going. */
public final class NearestCarDispatcher implements Dispatcher {
@Override public String name() { return "nearest-car"; }
@Override
public Car choose(List<Car> candidates, int floor, Direction dir) {
return candidates.stream()
.min(Comparator.comparingInt((Car c) -> Math.abs(c.floor() - floor)).thenComparingInt(Car::id))
.orElseThrow();
}
}
@@ -0,0 +1,35 @@
package com.ankurm.interviewlab.elevator;
/** One person making one trip. The three tick fields are filled in by the simulation. */
public final class Passenger {
private final String id;
private final int origin;
private final int destination;
private final long spawnTick;
private long boardedTick = -1;
private long arrivedTick = -1;
public Passenger(String id, int origin, int destination, long spawnTick) {
this.id = id;
this.origin = origin;
this.destination = destination;
this.spawnTick = spawnTick;
}
public String id() { return id; }
public int origin() { return origin; }
public int destination() { return destination; }
public Direction direction() { return Direction.between(origin, destination); }
public long spawnTick() { return spawnTick; }
void boardedAt(long tick) { this.boardedTick = tick; }
void arrivedAt(long tick) { this.arrivedTick = tick; }
public boolean delivered() { return arrivedTick >= 0; }
public long waitTicks() { return boardedTick - spawnTick; }
public long rideTicks() { return arrivedTick - boardedTick; }
public long totalTicks() { return arrivedTick - spawnTick; }
@Override
public String toString() { return id + "(" + origin + "->" + destination + ")"; }
}
@@ -0,0 +1,58 @@
package com.ankurm.interviewlab.elevator;
import java.util.ArrayList;
import java.util.List;
/**
* The scheduling question without the building: one car, a list of requested floors, how far does
* each policy make it travel? FCFS and SSTF are the two ideas people reach for first; LOOK is what
* the car in this module does.
*/
public final class PolicyComparison {
private PolicyComparison() { }
public record Result(String policy, List<Integer> order, int distance) { }
public static Result fcfs(int start, List<Integer> requests) {
return new Result("FCFS", List.copyOf(requests), distance(start, requests));
}
public static Result sstf(int start, List<Integer> requests) {
List<Integer> left = new ArrayList<>(requests);
List<Integer> order = new ArrayList<>();
int at = start;
while (!left.isEmpty()) {
int best = 0;
for (int i = 1; i < left.size(); i++) {
if (Math.abs(left.get(i) - at) < Math.abs(left.get(best) - at)) best = i;
}
at = left.remove(best);
order.add(at);
}
return new Result("SSTF", order, distance(start, order));
}
/** LOOK: sweep up serving everything above, then sweep down serving everything below (reverse if heading down). */
public static Result look(int start, boolean headingUp, List<Integer> requests) {
List<Integer> above = requests.stream().filter(f -> f >= start).sorted().toList();
List<Integer> below = requests.stream().filter(f -> f < start).sorted(java.util.Comparator.reverseOrder()).toList();
List<Integer> order = new ArrayList<>();
if (headingUp) { order.addAll(above); order.addAll(below); }
else {
List<Integer> belowFirst = requests.stream().filter(f -> f <= start).sorted(java.util.Comparator.reverseOrder()).toList();
List<Integer> aboveAfter = requests.stream().filter(f -> f > start).sorted().toList();
order.addAll(belowFirst); order.addAll(aboveAfter);
}
return new Result("LOOK", order, distance(start, order));
}
static int distance(int start, List<Integer> order) {
int at = start;
int total = 0;
for (int f : order) {
total += Math.abs(f - at);
at = f;
}
return total;
}
}
@@ -0,0 +1,14 @@
package com.ankurm.interviewlab.elevator;
import java.util.Locale;
/** Summary of one simulation run. Times are in ticks: one tick is one floor of travel. */
public record Report(String dispatcher, int passengers, int delivered, double avgWait, double avgRide, double avgTotal,
long maxWait, long maxTotal, int floorsTravelled, int doorCycles, long ticks) {
@Override
public String toString() {
return String.format(Locale.ROOT,
"%-12s delivered %d/%d wait avg %.1f max %d total avg %.1f max %d floors %d door cycles %d ticks %d",
dispatcher, delivered, passengers, avgWait, maxWait, avgTotal, maxTotal, floorsTravelled, doorCycles, ticks);
}
}
@@ -0,0 +1,15 @@
package com.ankurm.interviewlab.elevator;
import java.util.List;
/** A baseline that looks at nothing: cars take turns. */
public final class RoundRobinDispatcher implements Dispatcher {
private int next;
@Override public String name() { return "round-robin"; }
@Override
public Car choose(List<Car> candidates, int floor, Direction dir) {
return candidates.get(next++ % candidates.size());
}
}
@@ -0,0 +1,41 @@
package com.ankurm.interviewlab.elevator;
import java.util.List;
/** Feeds arrivals into a building tick by tick until everyone has been delivered. */
public final class Simulation {
private Simulation() { }
public static Report run(Building building, List<Arrival> arrivals, int maxTicks) {
return run(building, arrivals, maxTicks, b -> { });
}
/** As above, calling the observer after every tick: tests use it to check invariants. */
public static Report run(Building building, List<Arrival> arrivals, int maxTicks, java.util.function.Consumer<Building> observer) {
int next = 0;
long t = 0;
while (t < maxTicks && (next < arrivals.size() || building.deliveredPassengers().size() < arrivals.size())) {
while (next < arrivals.size() && arrivals.get(next).tick() <= t) {
Arrival a = arrivals.get(next);
building.submit(new Passenger("p" + next, a.origin(), a.destination(), t));
next++;
}
building.tick();
observer.accept(building);
t++;
}
return report(building, arrivals.size(), t);
}
static Report report(Building b, int total, long ticks) {
List<Passenger> done = b.deliveredPassengers();
double wait = done.stream().mapToLong(Passenger::waitTicks).average().orElse(0);
double ride = done.stream().mapToLong(Passenger::rideTicks).average().orElse(0);
double all = done.stream().mapToLong(Passenger::totalTicks).average().orElse(0);
long maxWait = done.stream().mapToLong(Passenger::waitTicks).max().orElse(0);
long maxAll = done.stream().mapToLong(Passenger::totalTicks).max().orElse(0);
int floors = b.cars().stream().mapToInt(Car::floorsTravelled).sum();
int doors = b.cars().stream().mapToInt(Car::doorCycles).sum();
return new Report(b.dispatcher().name(), total, done.size(), wait, ride, all, maxWait, maxAll, floors, doors, ticks);
}
}
@@ -0,0 +1,57 @@
package com.ankurm.interviewlab.elevator;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* One car on floors 0..9, one far request waiting at floor 0, and a steady trickle of new requests
* at floors 6 and 7. The car moves one floor per tick. How long does the far request wait under
* SSTF (always the nearest request) and under LOOK (finish the sweep, then turn)?
*/
public final class StarvationDemo {
private StarvationDemo() { }
public record Outcome(String policy, int farServedAtTick, int streamEndsAtTick) { }
public static Outcome run(boolean look, int streamTicks) {
int head = 5;
int dir = 1; // LOOK's current sweep direction: +1 up, -1 down
List<Integer> pending = new ArrayList<>();
pending.add(0);
for (int t = 1; t <= 1000; t++) {
if (t <= streamTicks) pending.add(t % 2 == 0 ? 6 : 7);
if (look) {
if (!anyAhead(pending, head, dir)) dir = -dir;
head += towards(pending, head, dir);
} else {
head += Integer.compare(nearest(pending, head), head);
}
for (Iterator<Integer> it = pending.iterator(); it.hasNext(); ) {
if (it.next() == head) it.remove();
}
if (!pending.contains(0)) return new Outcome(look ? "LOOK" : "SSTF", t, streamTicks);
}
return new Outcome(look ? "LOOK" : "SSTF", -1, streamTicks);
}
private static boolean anyAhead(List<Integer> pending, int head, int dir) {
for (int f : pending) {
if ((dir > 0 && f > head) || (dir < 0 && f < head)) return true;
}
return false;
}
/** One step towards the nearest pending request in the sweep direction (or standing still). */
private static int towards(List<Integer> pending, int head, int dir) {
return anyAhead(pending, head, dir) ? dir : 0;
}
private static int nearest(List<Integer> pending, int head) {
int best = pending.get(0);
for (int f : pending) {
if (Math.abs(f - head) < Math.abs(best - head)) best = f;
}
return best;
}
}
@@ -0,0 +1,12 @@
package com.ankurm.interviewlab.elevator;
/**
* A floor a car has promised to visit. A hall button gives a stop with a direction (UP or DOWN);
* a button inside the car gives a stop with direction NONE, served whichever way the car is going.
*/
public record Stop(int floor, Direction dir) {
@Override
public String toString() {
return dir == Direction.NONE ? String.valueOf(floor) : floor + dir.name().substring(0, 1).toLowerCase();
}
}
@@ -0,0 +1,47 @@
package com.ankurm.interviewlab.elevator;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Random;
/** Seeded passenger streams, so every run of a test sees exactly the same morning. */
public final class Traffic {
private Traffic() { }
/** Morning: 70% of people start at the lobby (floor 0) and go up; the rest travel between random floors. */
public static List<Arrival> upPeak(long seed, int people, int floors, int spreadTicks) {
Random rnd = new Random(seed);
List<Arrival> list = new ArrayList<>();
for (int i = 0; i < people; i++) {
long tick = rnd.nextInt(spreadTicks);
int origin;
int dest;
if (rnd.nextInt(100) < 70) {
origin = 0;
dest = 1 + rnd.nextInt(floors - 1);
} else {
origin = rnd.nextInt(floors);
do { dest = rnd.nextInt(floors); } while (dest == origin);
}
list.add(new Arrival(tick, origin, dest));
}
list.sort(Comparator.comparingLong(Arrival::tick));
return list;
}
/** Between floors: every person picks an origin and a different destination uniformly. */
public static List<Arrival> mixed(long seed, int people, int floors, int spreadTicks) {
Random rnd = new Random(seed);
List<Arrival> list = new ArrayList<>();
for (int i = 0; i < people; i++) {
long tick = rnd.nextInt(spreadTicks);
int origin = rnd.nextInt(floors);
int dest;
do { dest = rnd.nextInt(floors); } while (dest == origin);
list.add(new Arrival(tick, origin, dest));
}
list.sort(Comparator.comparingLong(Arrival::tick));
return list;
}
}
@@ -0,0 +1,31 @@
package com.ankurm.interviewlab.elevator;
import com.ankurm.interviewlab.elevator.support.Fixtures;
import com.ankurm.interviewlab.elevator.support.Transcript;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
class CapacityTest {
@Test
void fullCarLeavesPeopleBehindAndComesBack() {
Building b = new Building(8, new int[] {0}, 2, new NearestCarDispatcher());
Transcript out = Transcript.start("05-capacity.txt", "Capacity 2, five people at the lobby, all going UP");
for (int i = 0; i < 5; i++) b.submit(new Passenger("p" + i, 0, 2 + i, 0));
out.line("hall calls dispatched after five button presses: " + b.hallCallsDispatched()).blank();
Fixtures.tickUntilDelivered(b, 5, 200);
for (String line : b.log()) out.line(line);
out.blank();
for (Passenger p : b.deliveredPassengers()) {
out.line(String.format("%-8s wait %2d ride %2d", p, p.waitTicks(), p.rideTicks()));
}
out.flush();
assertEquals(5, b.deliveredPassengers().size());
assertEquals(List.of(0L, 0L, 15L, 15L, 34L), b.deliveredPassengers().stream().sorted(java.util.Comparator.comparing(Passenger::id)).map(Passenger::waitTicks).toList());
// Capacity 2 means three trips from floor 0.
assertEquals(3, Fixtures.doorOpenings(b, 0).stream().filter(f -> f == 0).count());
}
}
@@ -0,0 +1,83 @@
package com.ankurm.interviewlab.elevator;
import com.ankurm.interviewlab.elevator.support.Transcript;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.function.Supplier;
import static org.junit.jupiter.api.Assertions.assertEquals;
class DispatcherTest {
private static final int FLOORS = 12;
private static final int CARS = 3;
private record Run(Report report, int[] callsPerCar) { }
private static Run run(Supplier<Dispatcher> d, List<Arrival> traffic) {
Building b = Building.of(FLOORS, CARS, 8, d.get());
Report r = Simulation.run(b, traffic, 5000);
int[] calls = new int[CARS];
for (String line : b.log()) {
int i = line.indexOf(" -> car");
if (line.contains(" hall ") && i > 0) calls[line.charAt(i + 7) - '0']++;
}
return new Run(r, calls);
}
private static double one(double v) { return Math.round(v * 10) / 10.0; }
@Test
void threeDispatchersOnTwoKindsOfTraffic() {
Transcript out = Transcript.start("03-dispatchers.txt",
"12 floors, 3 cars (capacity 8), 120 people: same seeded traffic through three dispatchers");
out.line("Times are in ticks. 'wait' is button press to boarding; 'total' is button press to arrival.").blank();
List<Arrival> morning = Traffic.upPeak(42, 120, FLOORS, 240);
List<Arrival> between = Traffic.mixed(7, 120, FLOORS, 360);
List<Supplier<Dispatcher>> all = List.of(RoundRobinDispatcher::new, NearestCarDispatcher::new, EtaDispatcher::new);
out.line("Up-peak (70% start at the lobby), seed 42, arrivals spread over 240 ticks");
Report[] a = new Report[3];
for (int i = 0; i < 3; i++) {
Run run = run(all.get(i), morning);
a[i] = run.report();
out.line(" " + a[i]);
out.line(" hall calls per car (car0, car1, car2): " + java.util.Arrays.toString(run.callsPerCar()));
}
out.blank().line("Between floors (uniform origin and destination), seed 7, arrivals spread over 360 ticks");
Report[] c = new Report[3];
for (int i = 0; i < 3; i++) {
Run run = run(all.get(i), between);
c[i] = run.report();
out.line(" " + c[i]);
out.line(" hall calls per car (car0, car1, car2): " + java.util.Arrays.toString(run.callsPerCar()));
}
out.flush();
for (Report r : a) assertEquals(120, r.delivered());
for (Report r : c) assertEquals(120, r.delivered());
// Index 0 round-robin, 1 nearest-car, 2 eta. The figures quoted in the article:
assertEquals(18.5, one(a[0].avgWait())); assertEquals(91.9, one(a[1].avgWait())); assertEquals(13.7, one(a[2].avgWait()));
assertEquals(13.3, one(c[0].avgWait())); assertEquals(16.5, one(c[1].avgWait())); assertEquals(9.9, one(c[2].avgWait()));
assertEquals(248, a[1].maxWait()); assertEquals(43, a[2].maxWait());
}
@Test
void forecastOfAnIdleCarIsExact() {
Building b = Building.of(10, 1, 8, new EtaDispatcher());
Car car = b.cars().get(0); // idle at floor 0
int predicted = car.eta(7, Direction.UP);
b.submit(new Passenger("x", 7, 9, 0));
int ticks = 0;
while (b.deliveredPassengers().isEmpty() && b.waitingCount() == 1 && car.riderCount() == 0 && ticks < 100) {
b.tick();
ticks++;
}
// The doors open on the tick after `predicted - 1` ticks of movement: tick numbering starts at 1 in eta().
Transcript.start("03b-eta-forecast.txt", "ETA forecast for an idle car at floor 0 and a call at floor 7 (UP)")
.line("predicted: " + predicted + " ticks").line("actual: " + ticks + " ticks").flush();
assertEquals(predicted, ticks);
}
}
@@ -0,0 +1,56 @@
package com.ankurm.interviewlab.elevator;
import com.ankurm.interviewlab.elevator.support.Transcript;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.function.Supplier;
import static org.junit.jupiter.api.Assertions.assertEquals;
class InvariantsTest {
/** Rules that must hold after every single tick of every run. */
private static void check(Building b) {
for (Car c : b.cars()) {
if (c.floor() < 0 || c.floor() >= b.floors()) throw new AssertionError(c + " is outside the shaft");
if (c.riderCount() > c.capacity()) throw new AssertionError(c + " is over capacity");
for (Passenger p : c.riders()) {
if (p.destination() != c.floor() && !c.stops().contains(new Stop(p.destination(), Direction.NONE))) {
throw new AssertionError(c + " carries " + p + " but has no stop for them");
}
}
if (c.stateName().equals("DOORS_OPEN") && c.heading() == Direction.NONE && c.riderCount() > 0 && c.stops().isEmpty()) {
throw new AssertionError(c + " is stuck with riders and no stops");
}
}
}
@Test
void everyoneArrivesAndNoRuleIsBroken() {
Transcript out = Transcript.start("07-invariants.txt",
"Randomised runs: 150 seeds x 3 dispatchers x 2 traffic shapes, rules checked after every tick");
List<Supplier<Dispatcher>> all = List.of(RoundRobinDispatcher::new, NearestCarDispatcher::new, EtaDispatcher::new);
int runs = 0;
long ticks = 0;
int people = 0;
for (Supplier<Dispatcher> d : all) {
for (int seed = 1; seed <= 150; seed++) {
for (int shape = 0; shape < 2; shape++) {
List<Arrival> traffic = shape == 0 ? Traffic.upPeak(seed, 40, 10, 80) : Traffic.mixed(seed, 40, 10, 120);
Building b = Building.of(10, 3, 4, d.get());
Report r = Simulation.run(b, traffic, 3000, InvariantsTest::check);
assertEquals(40, r.delivered(), "seed " + seed + " " + r.dispatcher());
runs++;
ticks += r.ticks();
people += r.delivered();
}
}
}
out.line("runs: " + runs).line("people delivered: " + people).line("simulated ticks checked: " + ticks)
.line("rule violations: 0").flush();
assertEquals(900, runs);
assertEquals(36000, people);
assertEquals(137430L, ticks);
}
}
@@ -0,0 +1,67 @@
package com.ankurm.interviewlab.elevator;
import com.ankurm.interviewlab.elevator.support.Fixtures;
import com.ankurm.interviewlab.elevator.support.Transcript;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class MaintenanceTest {
@Test
void carFinishesItsRidersThenLeavesService() {
Building b = new Building(10, new int[] {0, 9}, 8, new NearestCarDispatcher());
Transcript out = Transcript.start("04-maintenance.txt", "Taking car0 out of service while it carries a passenger");
Car car0 = b.cars().get(0);
Car car1 = b.cars().get(1);
b.submit(new Passenger("a", 0, 5, 0)); // car0 takes this one
for (int i = 0; i < 5; i++) b.tick();
car0.requestMaintenance();
out.line("t=5: maintenance requested for car0, which is carrying 'a' to floor 5").blank();
b.submit(new Passenger("b", 2, 6, 5)); // nearer to car0, but car0 may not accept work now
int t = 5;
while (!car0.inMaintenance() && t < 100) {
b.tick();
out.line(String.format("t=%02d %s", t, Fixtures.snapshot(b)));
t++;
}
out.blank().line("car0 entered MAINTENANCE at tick " + (t - 1) + " at floor " + car0.floor());
assertEquals(12, t - 1);
out.line("hall call for 'b' went to: " + b.log().stream().filter(l -> l.contains("hall 2u")).findFirst().orElse("?"));
assertTrue(car0.inMaintenance());
assertTrue(b.deliveredPassengers().stream().anyMatch(p -> p.id().equals("a")));
assertTrue(b.log().stream().anyMatch(l -> l.contains("hall 2u -> car1")));
// Put it back and check it takes work again.
car0.returnToService();
assertFalse(car0.inMaintenance());
b.submit(new Passenger("c", car0.floor(), 9, t));
for (int i = 0; i < 3; i++) b.tick();
out.blank().line("after returnToService(): " + Fixtures.snapshot(b).split("\\|")[0].trim());
out.flush();
assertEquals(1, car0.riderCount() + (int) b.deliveredPassengers().stream().filter(p -> p.id().equals("c")).count());
}
@Test
void callsWaitWhenEveryCarIsOutOfService() {
Building b = Building.of(10, 2, 8, new EtaDispatcher());
for (Car c : b.cars()) c.requestMaintenance();
b.tick();
assertTrue(b.cars().stream().allMatch(Car::inMaintenance));
b.submit(new Passenger("lonely", 4, 1, 1));
for (int i = 0; i < 10; i++) b.tick();
Transcript out = Transcript.start("04b-all-cars-out.txt", "Both cars out of service, one person presses a button");
out.line("after 10 ticks: delivered=" + b.deliveredPassengers().size() + " waiting=" + b.waitingCount());
b.cars().get(1).returnToService();
int t = 0;
while (b.deliveredPassengers().isEmpty() && t < 60) { b.tick(); t++; }
out.line("car1 returned to service: delivered after " + t + " more ticks");
out.flush();
assertEquals(1, b.deliveredPassengers().size());
assertEquals(11, t);
}
}
@@ -0,0 +1,48 @@
package com.ankurm.interviewlab.elevator;
import com.ankurm.interviewlab.elevator.support.Fixtures;
import com.ankurm.interviewlab.elevator.support.Transcript;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
class PitfallsTest {
/** Car0 is about to head down from floor 4; car1 is parked at 9. A person at floor 3 wants to go UP. */
private static long waitOfPersonAtThree(Dispatcher d, Transcript out) {
Building b = new Building(10, new int[] {4, 9}, 8, d);
b.submit(new Passenger("rider", 4, 0, 0)); // car0 is at 4: picks 'rider' up and heads DOWN
for (int i = 0; i < 4; i++) b.tick(); // doors open, then the car starts down
out.line(d.name() + ": after 4 ticks " + Fixtures.snapshot(b).split("\\|")[0].trim());
b.submit(new Passenger("p3", 3, 8, 4)); // presses UP at floor 3
Fixtures.tickUntilDelivered(b, 2, 200);
String assigned = b.log().stream().filter(l -> l.contains("hall 3u")).findFirst().orElse("?");
out.line(d.name() + ": " + assigned);
return Fixtures.find(b, "p3").waitTicks();
}
@Test
void nearestCarIgnoresWhichWayTheCarIsGoing() {
Transcript out = Transcript.start("08-nearest-car-trap.txt", "Hall call UP at floor 3 while car0 (at 4) is going DOWN and car1 waits at 9");
long nearest = waitOfPersonAtThree(new NearestCarDispatcher(), out);
long eta = waitOfPersonAtThree(new EtaDispatcher(), out);
out.blank().line("wait for the person at floor 3, in ticks:").line(" nearest-car " + nearest).line(" eta " + eta);
out.flush();
assertTrue(eta < nearest);
}
@Test
void fivePeoplePressingTheSameButtonMakeOneHallCall() {
Building b = Building.of(10, 2, 8, new EtaDispatcher());
for (int i = 0; i < 5; i++) b.submit(new Passenger("p" + i, 6, 9, 0));
Transcript out = Transcript.start("08b-same-button.txt", "Five people at floor 6 all press UP");
out.line("hall calls dispatched: " + b.hallCallsDispatched());
Fixtures.tickUntilDelivered(b, 5, 200);
long opens = b.cars().stream().mapToInt(Car::doorCycles).sum();
out.line("door cycles used to serve all five: " + opens);
out.flush();
assertEquals(1, b.hallCallsDispatched());
assertEquals(2, opens); // one stop at floor 6 to board, one at floor 9 to alight
}
}
@@ -0,0 +1,42 @@
package com.ankurm.interviewlab.elevator;
import com.ankurm.interviewlab.elevator.support.Transcript;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
class PolicyTest {
@Test
void distanceUnderThreePolicies() {
List<Integer> requests = List.of(8, 2, 9, 1, 6, 3);
Transcript out = Transcript.start("02-policies.txt", "One car at floor 5 heading up, six requests: floors travelled");
out.line("requests in arrival order: " + requests).blank();
var fcfs = PolicyComparison.fcfs(5, requests);
var sstf = PolicyComparison.sstf(5, requests);
var look = PolicyComparison.look(5, true, requests);
for (var r : List.of(fcfs, sstf, look)) {
out.line(String.format("%-5s order %-24s distance %d", r.policy(), r.order(), r.distance()));
}
out.flush();
assertEquals(32, fcfs.distance());
assertEquals(12, sstf.distance());
assertEquals(12, look.distance());
}
@Test
void sstfStarvesTheFarRequestAndLookDoesNot() {
Transcript out = Transcript.start("02b-starvation.txt",
"A request waits at floor 0; the car is at floor 5; new requests keep appearing at floors 6 and 7");
var sstf = StarvationDemo.run(false, 40);
var look = StarvationDemo.run(true, 40);
out.line("The stream of new requests lasts 40 ticks. The car moves one floor per tick.").blank();
out.line(String.format("%-5s far request served at tick %d", sstf.policy(), sstf.farServedAtTick()));
out.line(String.format("%-5s far request served at tick %d", look.policy(), look.farServedAtTick()));
out.flush();
assertEquals(46, sstf.farServedAtTick());
assertEquals(9, look.farServedAtTick());
}
}
@@ -0,0 +1,49 @@
package com.ankurm.interviewlab.elevator;
import com.ankurm.interviewlab.elevator.support.Fixtures;
import com.ankurm.interviewlab.elevator.support.Transcript;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
class TraceTest {
@Test
void oneCarThreePeopleTickByTick() {
Building b = new Building(10, new int[] {0}, 8, new NearestCarDispatcher());
Transcript out = Transcript.start("01-single-car-trace.txt",
"One car, three people, one tick per line (floors 0..9, doors stay open 3 ticks)");
out.line("p0 starts at 0 and wants 6 (UP). p1 starts at 4 and wants 8 (UP). p2 starts at 3 and wants 1 (DOWN).")
.line("All three press their button at tick 0.").blank();
b.submit(new Passenger("p0", 0, 6, 0));
b.submit(new Passenger("p1", 4, 8, 0));
b.submit(new Passenger("p2", 3, 1, 0));
int t = 0;
while (b.deliveredPassengers().size() < 3 && t < 100) {
b.tick();
out.line(String.format("t=%02d %s", t, Fixtures.snapshot(b)));
t++;
}
out.blank().line("Door openings (from the building log):");
for (String line : b.log()) if (line.contains("opens at")) out.line(" " + line);
out.blank().line("Per person (ticks): wait = button to boarding, ride = boarding to arrival");
for (String id : List.of("p0", "p1", "p2")) {
Passenger p = Fixtures.find(b, id);
out.line(String.format(" %-3s %-8s wait %2d ride %2d total %2d", id, p, p.waitTicks(), p.rideTicks(), p.totalTicks()));
}
out.flush();
assertEquals(List.of(0, 4, 6, 8, 3, 1), Fixtures.doorOpenings(b, 0));
// p2 pressed DOWN at floor 3 while the car was going UP: the car passed floor 3 twice before stopping.
assertEquals(3, b.deliveredPassengers().size());
assertEquals(0, Fixtures.find(b, "p0").waitTicks());
assertEquals(7, Fixtures.find(b, "p1").waitTicks());
assertEquals(25, Fixtures.find(b, "p2").waitTicks());
assertEquals(30, Fixtures.find(b, "p2").totalTicks());
}
}
@@ -0,0 +1,44 @@
package com.ankurm.interviewlab.elevator;
import com.ankurm.interviewlab.elevator.support.Transcript;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class ValidationTest {
private record Bad(String what, Passenger passenger, String message) { }
@Test
void badRequestsAreRejectedWithAMessage() {
Building b = Building.of(10, 1, 8, new EtaDispatcher());
Transcript out = Transcript.start("06-validation.txt", "Requests the building refuses, and the exact message");
List<Bad> cases = List.of(
new Bad("origin above the top floor", new Passenger("a", 12, 3, 0), "origin floor 12 is outside 0..9"),
new Bad("origin below the ground floor", new Passenger("b", -1, 3, 0), "origin floor -1 is outside 0..9"),
new Bad("destination above the top floor", new Passenger("c", 2, 10, 0), "destination floor 10 is outside 0..9"),
new Bad("destination below the ground floor", new Passenger("d", 2, -4, 0), "destination floor -4 is outside 0..9"),
new Bad("same origin and destination", new Passenger("e", 5, 5, 0), "origin and destination are both floor 5"));
for (Bad bad : cases) {
var ex = assertThrows(IllegalArgumentException.class, () -> b.submit(bad.passenger()));
out.line(String.format("%-36s -> %s", bad.what(), ex.getMessage()));
assertEquals(bad.message(), ex.getMessage());
}
out.blank().line("people waiting afterwards: " + b.waitingCount() + ", hall calls dispatched: " + b.hallCallsDispatched());
out.flush();
assertEquals(0, b.waitingCount());
assertEquals(0, b.hallCallsDispatched());
}
@Test
void carRefusesAStopOutsideItsShaft() {
Car car = new Car(0, 0, 9, 0, 8);
var ex = assertThrows(IllegalArgumentException.class, () -> car.addStop(new Stop(10, Direction.NONE)));
Transcript.start("06b-stop-outside-shaft.txt", "A stop above the top floor")
.line("addStop(10) -> " + ex.getMessage()).flush();
assertEquals("floor 10 is outside 0..9", ex.getMessage());
}
}
@@ -0,0 +1,44 @@
package com.ankurm.interviewlab.elevator.support;
import com.ankurm.interviewlab.elevator.Building;
import com.ankurm.interviewlab.elevator.Car;
import com.ankurm.interviewlab.elevator.Passenger;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public final class Fixtures {
private Fixtures() { }
/** One line describing every car right now. */
public static String snapshot(Building b) {
StringBuilder sb = new StringBuilder();
for (Car c : b.cars()) {
if (sb.length() > 0) sb.append(" | ");
sb.append(String.format("car%d floor %2d %-11s %-4s stops %-18s riders %s",
c.id(), c.floor(), c.stateName(), c.heading(), c.stops(), c.riders()));
}
return sb.toString();
}
/** Floors where doors opened, in order, read from the building log. */
public static List<Integer> doorOpenings(Building b, int carId) {
Pattern p = Pattern.compile("car" + carId + " opens at (\\d+) ");
List<Integer> floors = new ArrayList<>();
for (String line : b.log()) {
Matcher m = p.matcher(line);
if (m.find()) floors.add(Integer.parseInt(m.group(1)));
}
return floors;
}
public static void tickUntilDelivered(Building b, int people, int maxTicks) {
for (int i = 0; i < maxTicks && b.deliveredPassengers().size() < people; i++) b.tick();
}
public static Passenger find(Building b, String id) {
return b.deliveredPassengers().stream().filter(p -> p.id().equals(id)).findFirst().orElseThrow();
}
}
@@ -0,0 +1,43 @@
package com.ankurm.interviewlab.elevator.support;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
/** Writes output/NN-*.txt while the calling test asserts the same numbers it prints. */
public final class Transcript {
private final Path path;
private final List<String> lines = new ArrayList<>();
private Transcript(Path path, String header) {
this.path = path;
lines.add(header);
lines.add("=".repeat(Math.min(header.length(), 100)));
lines.add("");
}
public static Transcript start(String fileName, String header) {
Path dir = Path.of("output");
try {
Files.createDirectories(dir);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return new Transcript(dir.resolve(fileName), header);
}
public Transcript line(String text) { lines.add(text); return this; }
public Transcript blank() { lines.add(""); return this; }
public void flush() {
try {
Files.write(path, (String.join("\n", lines) + "\n").getBytes(StandardCharsets.UTF_8));
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}