-
Notifications
You must be signed in to change notification settings - Fork 3.3k
/
Copy pathElevatorController.cs
49 lines (43 loc) · 1.43 KB
/
ElevatorController.cs
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
38
39
40
41
42
43
44
45
46
47
48
49
using System;
using System.Collections.Generic;
using System.Threading;
namespace ElevatorSystem
{
public class ElevatorController
{
private readonly List<Elevator> elevators;
public ElevatorController(int numElevators, int capacity)
{
elevators = new List<Elevator>();
for (int i = 0; i < numElevators; i++)
{
Elevator elevator = new Elevator(i + 1, capacity);
elevators.Add(elevator);
new Thread(elevator.Run).Start(); // Start elevator thread
}
}
public void RequestElevator(int sourceFloor, int destinationFloor)
{
Elevator optimalElevator = FindOptimalElevator(sourceFloor);
if (optimalElevator != null)
{
optimalElevator.AddRequest(new Request(sourceFloor, destinationFloor));
}
}
private Elevator FindOptimalElevator(int sourceFloor)
{
Elevator optimalElevator = null;
int minDistance = int.MaxValue;
foreach (Elevator elevator in elevators)
{
int distance = Math.Abs(sourceFloor - elevator.CurrentFloor);
if (distance < minDistance)
{
minDistance = distance;
optimalElevator = elevator;
}
}
return optimalElevator;
}
}
}