-
Notifications
You must be signed in to change notification settings - Fork 0
/
ElevatorSystem.m
86 lines (66 loc) · 1.86 KB
/
ElevatorSystem.m
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/**
* Implementation
*
* Elevator.m
*
* Created by Colin Scott-Fleming on 2012-11-09
*/
#import "ElevatorSystem.h"
@interface ElevatorSystem()
-(Elevator *)selectBestElevatorForFloor:(int)floor;
@end
@implementation ElevatorSystem
@synthesize elevators;
@synthesize totalServiceRequests;
- (id) init {
self = [super init];
/* Starting with 3 elevators for initial implementation */
self.elevators = [[NSMutableArray alloc] init];
[self.elevators addObject: [[Elevator alloc] init]];
[self.elevators addObject: [[Elevator alloc] init]];
[self.elevators addObject: [[Elevator alloc] init]];
return self;
}
/**
* Process a service request from a floor.
*/
- (void) serviceRequestFromFloor:(int)floor {
Elevator *selection = [self selectBestElevatorForFloor:floor];
/**
* Add the service request only if we have an elevator not in Maintenance
* Mode.
*/
if (selection) {
[selection addServiceRequestForFloor:floor];
self.totalServiceRequests++;
}
}
/**
* Selects the best elevator from the array of elevators.
*/
- (Elevator *)selectBestElevatorForFloor:(int)floor {
/* Just pick the closest elevator not in Maintenance Mode for now.
*
* This does not take the current elevator direction into account, but this
* functionality can be added later (again time constraints).
*/
Elevator *selection = [self.elevators objectAtIndex: 0];
for (Elevator *other in self.elevators)
if (abs(other.currentFloor - floor) <
abs(selection.currentFloor - floor) &&
!other.isInMaintenanceMode) {
selection = other;
}
// If all elevators are in Maintenance Mode, return nil.
if (selection.isInMaintenanceMode) {
return nil;
}
return selection;
}
- (void) addElevator {
[self.elevators addObject:[[Elevator alloc] init]];
}
- (void) dealloc {
self.elevators = nil;
}
@end