// Complete the elevator requests public void DoRequests() { if (RequestsQueue.Count > 0) { // Make sure queue is sorted before any request is completed SortRequestsQueue(); Request requestToComplete = RequestsQueue[0]; // Go to requested floor if (Door.Status != "closed") { Door.CloseDoor(); } NextFloor = requestToComplete.Floor; GoToNextFloor(); // Remove request after it is complete Door.OpenDoor(); RequestsQueue.Remove(requestToComplete); // Automatically close door Door.CloseDoor(); } // Automatically go idle temporarily if 0 requests or at the end of request Movement = "idle"; }
// Sort requests, for added efficiency private void SortRequestsQueue() { // Remove any requests which are useless i.e. requests that are already on their desired floor foreach (var req in RequestsQueue.ToArray()) { if (req.Floor == CurrentFloor) { RequestsQueue.Remove(req); } } // Decide if elevator is going up, down or is staying idle SetMovement(); // Sort if (RequestsQueue.Count > 1) { if (Movement == "up") { // Sort the queue in ascending order RequestsQueue.Sort((x, y) => x.Floor.CompareTo(y.Floor)); // Push any request to the end of the queue that would require a direction change foreach (var req in RequestsQueue.ToArray()) { if (req.Direction != Movement || req.Floor < CurrentFloor) { RequestsQueue.Remove(req); RequestsQueue.Add(req); } } } else { // Reverse the sorted queue (will now be in descending order) RequestsQueue.Sort((x, y) => y.Floor.CompareTo(x.Floor)); // Push any request to the end of the queue that would require a direction change foreach (var req in RequestsQueue.ToArray()) { if (req.Direction != Movement || req.Floor > CurrentFloor) { RequestsQueue.Remove(req); RequestsQueue.Add(req); } } } } }