Skip to content
Java project #23Advanced

Elevator Simulator

A tick-based simulation of two elevators using the SCAN algorithm, cost-based dispatching, capacity limits and re-dispatching, with wait-time and journey statistics.

Estimated time
~8 hours to build
Files
6 files · 397 lines
Technologies
Java 21, TreeSet (ceiling/floor queries), Records, Streams

Introduction

Elevator control is a classic discrete-event simulation: the world advances in ticks, each car follows its own rules, and a dispatcher decides who serves each call. Because nothing here depends on wall-clock time or threads, the same input always produces the same, testable log.

Problem statement

Simulate a 10-floor building with two cars of different capacity. Requests arrive at given ticks with a start floor, a destination and a group size; reject invalid ones (same floor, out-of-range floors, groups larger than any car). Assign each request to the car with the lowest estimated cost, move cars one floor per tick using SCAN (keep going while there are stops ahead, then reverse), open doors to let passengers off and on, and when a car is too full, leave the group waiting and re-dispatch them to a car with room. Log every event and finish with average wait and journey times, the longest journey and floors travelled per car.

Objectives

  • Design a deterministic discrete-time simulation
  • Implement the SCAN scheduling algorithm
  • Write a cost function for dispatching
  • Handle capacity limits without deadlocking the simulation

Features

  • Two cars with different capacities
  • SCAN movement with direction reversal
  • Cost-based dispatch and re-dispatch when full
  • Event log and performance statistics

Concepts demonstrated

  • Simulation
  • Scheduling algorithms
  • State machines
  • Heuristics
  • Statistics

System architecture

Elevator holds its floor, direction and a TreeSet of stops; tick() either opens the doors at a stop or moves one floor, reversing when ceiling/floor show no stops ahead. costTo estimates how long the car would take to reach a call, cheap if the call is ahead in the same direction. Building.run loops over ticks: dispatch new requests, re-dispatch deferred ones, then tick every car and process boarding and alighting. Trips that don't fit are marked deferred instead of re-adding a stop, which avoids a car reopening its doors at the same floor forever.

Folder structure

TextProject tree
elevator-simulator/
├── README.md
├── src/Building.java
├── src/Elevator.java
├── src/Main.java
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

src/Building.java

120 lines
Javasrc/Building.java
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
/**
* A building with several elevators and a dispatcher. Passengers request trips (from, to) at a
* given tick; the dispatcher assigns each request to the car with the lowest estimated cost.
* The simulation is a discrete-time loop, so the same input always gives the same output.
*/
public class Building {
public record Request(int id, int tick, int from, int to, int people) { }
private static final class Trip {
final Request r;
Elevator car; // may change if the first car arrives full
boolean pickedUp, deferred;
int pickupTick = -1, doneTick = -1;
Trip(Request r, Elevator car) { this.r = r; this.car = car; }
}
private final int floors;
private final List<Elevator> cars = new ArrayList<>();
private final List<Trip> trips = new ArrayList<>();
private final List<String> log = new ArrayList<>();
public Building(int floors) { this.floors = floors; }
public void addElevator(Elevator e) { cars.add(e); }
public void validate(Request r) {
if (r.from() < 0 || r.from() >= floors || r.to() < 0 || r.to() >= floors) throw new IllegalArgumentException("floors are 0-" + (floors - 1));
if (r.from() == r.to()) throw new IllegalArgumentException("from and to are the same floor");
if (r.people() < 1) throw new IllegalArgumentException("at least one person");
int maxCap = cars.stream().mapToInt(Elevator::capacity).max().orElse(0);
if (r.people() > maxCap) throw new IllegalArgumentException("group of " + r.people() + " is larger than any car (" + maxCap + ")");
}
/** Runs the simulation until every request is delivered (or a safety limit is reached). */
public List<String> run(List<Request> requests) {
List<Request> pending = new ArrayList<>(requests);
pending.sort(Comparator.comparingInt(Request::tick).thenComparingInt(Request::id));
for (int tick = 0; tick < 10_000; tick++) {
// 1. New hall calls at this tick are dispatched to the cheapest car with room.
while (!pending.isEmpty() && pending.get(0).tick() == tick) {
Request r = pending.remove(0);
Elevator.Direction dir = r.to() > r.from() ? Elevator.Direction.UP : Elevator.Direction.DOWN;
Elevator best = cars.stream().filter(c -> c.capacity() >= r.people())
.min(Comparator.comparingInt((Elevator c) -> c.costTo(r.from(), dir)).thenComparing(Elevator::name)).get();
best.addStop(r.from());
trips.add(new Trip(r, best));
log.add(String.format("t=%-3d request #%d: %d person(s) %d -> %d assigned to %s (at floor %d)", tick, r.id(), r.people(), r.from(), r.to(), best.name(), best.floor()));
}
// 1b. Requests left behind by a full car go to the cheapest car that now has room.
final int now = tick;
for (Trip t : trips) {
if (!t.deferred) continue;
Elevator.Direction dir = t.r.to() > t.r.from() ? Elevator.Direction.UP : Elevator.Direction.DOWN;
cars.stream().filter(c -> c.capacity() - c.passengers() >= t.r.people())
.min(Comparator.comparingInt((Elevator c) -> c.costTo(t.r.from(), dir)).thenComparing(Elevator::name))
.ifPresent(c -> {
t.deferred = false;
t.car = c;
c.addStop(t.r.from());
log.add(String.format("t=%-3d request #%d re-assigned to %s", now, t.r.id(), c.name()));
});
}
// 2. Every car advances one tick; when doors open, passengers get off and on.
for (Elevator car : cars) {
boolean opened = car.tick() || (car.isIdle() && hasWaiting(car));
if (!opened) continue;
StringBuilder event = new StringBuilder();
for (Trip t : trips) {
if (t.car != car) continue;
if (t.pickedUp && t.doneTick < 0 && t.r.to() == car.floor()) {
car.alight(t.r.people());
t.doneTick = tick;
event.append(" #").append(t.r.id()).append(" off");
}
}
for (Trip t : trips) {
if (t.car != car || t.pickedUp || t.r.from() != car.floor() || t.r.tick() > tick) continue;
if (t.deferred) continue;
if (car.passengers() + t.r.people() > car.capacity()) {
t.deferred = true; // too full: the dispatcher will find a car with room
event.append(" #").append(t.r.id()).append(" waits (car full)");
continue;
}
car.board(t.r.people());
t.pickedUp = true;
t.pickupTick = tick;
car.addStop(t.r.to());
event.append(" #").append(t.r.id()).append(" on");
}
if (!event.isEmpty())
log.add(String.format("t=%-3d %s doors open at floor %d:%s (%d aboard)", tick, car.name(), car.floor(), event, car.passengers()));
}
if (pending.isEmpty() && trips.stream().allMatch(t -> t.doneTick >= 0)) {
log.add("All passengers delivered by t=" + tick);
break;
}
}
return log;
}
private boolean hasWaiting(Elevator car) {
return trips.stream().anyMatch(t -> t.car == car && !t.pickedUp && !t.deferred && t.r.from() == car.floor());
}
public List<String> report() {
List<String> out = new ArrayList<>();
double avgWait = trips.stream().mapToInt(t -> t.pickupTick - t.r.tick()).average().orElse(0);
double avgTrip = trips.stream().mapToInt(t -> t.doneTick - t.r.tick()).average().orElse(0);
Trip longest = trips.stream().max(Comparator.comparingInt((Trip t) -> t.doneTick - t.r.tick()).thenComparingInt(t -> -t.r.id())).orElse(null);
out.add(String.format("Requests: %d average wait %.1f ticks average journey %.1f ticks", trips.size(), avgWait, avgTrip));
if (longest != null) out.add("Longest journey: #" + longest.r.id() + " (" + (longest.doneTick - longest.r.tick()) + " ticks)");
for (Elevator c : cars) out.add(String.format(" %s: %d floors travelled, %d trip(s), now at floor %d", c.name(), c.floorsTravelled(), trips.stream().filter(t -> t.car == c).count(), c.floor()));
return out;
}
}

What each file does

src/Elevator.java
One car: SCAN movement, stops, passengers and the dispatch cost estimate.
src/Building.java
Requests, dispatching, the tick loop, boarding/alighting, re-dispatch and the report.
src/Main.java
Reads and validates requests, runs the simulation and prints the log.

How to run it

Compile

Terminal
javac -d out $(find src -name "*.java")
# Windows PowerShell: javac -d out (Get-ChildItem -Recurse src -Filter *.java).FullName

Run

Terminal
java -cp out Main

Test against the expected output

Terminal
java -cp out Main < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt
# Windows PowerShell:
# Get-Content tests\sample-input.txt | java -cp out Main > actual.txt

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
Line 6 skipped: from and to are the same floor
Line 7 skipped: floors are 0-9
Line 9 skipped: group of 9 is larger than any car (6)
Line 12 skipped: numbers expected
Simulating 7 request(s): car A at floor 0 (capacity 6), car B at floor 9 (capacity 4)
t=0 request #1: 2 person(s) 0 -> 7 assigned to A (at floor 0)
t=0 request #2: 1 person(s) 8 -> 1 assigned to B (at floor 9)
t=0 A doors open at floor 0: #1 on (2 aboard)
t=1 request #3: 1 person(s) 3 -> 9 assigned to B (at floor 8)
t=1 B doors open at floor 8: #2 on (1 aboard)
t=2 request #4: 3 person(s) 5 -> 0 assigned to B (at floor 8)
t=4 request #5: 2 person(s) 6 -> 2 assigned to B (at floor 6)
t=4 B doors open at floor 6: #5 on (3 aboard)
t=6 request #6: 4 person(s) 1 -> 8 assigned to B (at floor 5)
t=6 B doors open at floor 5: #4 waits (car full) (3 aboard)
t=7 request #7: 2 person(s) 9 -> 0 assigned to A (at floor 6)
t=7 request #4 re-assigned to A
t=8 A doors open at floor 7: #1 off (0 aboard)
t=9 B doors open at floor 3: #3 on (4 aboard)
t=11 A doors open at floor 9: #7 on (2 aboard)
t=11 B doors open at floor 2: #5 off (2 aboard)
t=13 B doors open at floor 1: #2 off #6 waits (car full) (1 aboard)
t=14 request #6 re-assigned to A
t=16 A doors open at floor 5: #4 on (5 aboard)
t=21 A doors open at floor 1: #6 waits (car full) (5 aboard)
t=22 B doors open at floor 9: #3 off (0 aboard)
t=23 request #6 re-assigned to B
t=23 A doors open at floor 0: #4 off #7 off (0 aboard)
t=31 B doors open at floor 1: #6 on (4 aboard)
t=39 B doors open at floor 8: #6 off (0 aboard)
All passengers delivered by t=39
Requests: 7 average wait 7.4 ticks average journey 17.0 ticks
Longest journey: #6 (33 ticks)
A: 18 floors travelled, 3 trip(s), now at floor 0
B: 31 floors travelled, 4 trip(s), now at floor 8
Input
# tick from to [people]
0 0 7 2
0 8 1
1 3 9 1
2 5 0 3
2 5 5
3 12 2
4 6 2 2
4 0 4 9
6 1 8 4
7 9 0 2
x 1 2

Testing

  • Run with tests/sample-input.txt and compare with tests/expected-output.txt.
  • Request #4 (3 people) finds car B full at floor 5 and is re-assigned to car A.
  • All seven valid requests are delivered by tick 39; four invalid lines are reported first.
  • Running the simulation twice gives identical output because it uses no threads or timers.

Common errors

A car keeps opening its doors at the same floor

When a group can't board, don't add the same stop again; defer the trip and re-dispatch it later.

Cars oscillate between two floors

Only reverse direction when there are no stops ahead in the current direction (SCAN).

Possible improvements

  • Add more cars and an express car serving only some floors
  • Use LOOK or destination-dispatch algorithms and compare statistics
  • Generate random traffic for morning and evening peaks

Additional challenges

  1. 1Minimise average wait by tuning the cost function.
  2. 2Add a maintenance mode that takes a car out of service.
  3. 3Draw the building as ASCII art each tick.

Built and tested it yourself? Mark it to update your dashboard.