-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
ElevatorController.java
37 lines (30 loc) · 1.18 KB
/
ElevatorController.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package elevatorsystem;
import java.util.ArrayList;
import java.util.List;
public class ElevatorController {
private final List<Elevator> elevators;
public ElevatorController(int numElevators, int capacity) {
elevators = new ArrayList<>();
for (int i = 0; i < numElevators; i++) {
Elevator elevator = new Elevator(i + 1, capacity);
elevators.add(elevator);
new Thread(elevator::run).start();
}
}
public void requestElevator(int sourceFloor, int destinationFloor) {
Elevator optimalElevator = findOptimalElevator(sourceFloor, destinationFloor);
optimalElevator.addRequest(new Request(sourceFloor, destinationFloor));
}
private Elevator findOptimalElevator(int sourceFloor, int destinationFloor) {
Elevator optimalElevator = null;
int minDistance = Integer.MAX_VALUE;
for (Elevator elevator : elevators) {
int distance = Math.abs(sourceFloor - elevator.getCurrentFloor());
if (distance < minDistance) {
minDistance = distance;
optimalElevator = elevator;
}
}
return optimalElevator;
}
}