diff options
author | raylu <lurayl@gmail.com> | 2016-02-22 20:00:40 -0800 |
---|---|---|
committer | raylu <lurayl@gmail.com> | 2016-02-22 20:00:40 -0800 |
commit | c4bfe29b8fb90ea805201f6b741d757bc49f59d4 (patch) | |
tree | 306e37de0163105a3168f91c45d4f311fb3291c3 /elevator.py | |
parent | 416aacc6f6e4ee8a988406ad4a5bc4fa69136564 (diff) | |
download | elevator-c4bfe29b8fb90ea805201f6b741d757bc49f59d4.tar.xz |
elevator direction, multiple dropoffs
Diffstat (limited to 'elevator.py')
-rwxr-xr-x | elevator.py | 49 |
1 files changed, 42 insertions, 7 deletions
diff --git a/elevator.py b/elevator.py index eec0b44..4a60ece 100755 --- a/elevator.py +++ b/elevator.py @@ -7,6 +7,37 @@ class Elevator: self.id = e_id self.floor = floor self.goal = goal + self.dropoffs = [] + + def direction(self): + if self.goal is None: + return None + if self.goal > self.floor: + return Direction.UP + else: + return Direction.DOWN + + def dropoff(self, floor): + if floor in self.dropoffs: + assert self.goal is not None + return + assert floor != self.floor + + if self.goal is None: + self.goal = floor + self.dropoffs.append(floor) + else: + direction = self.direction() + if direction == Direction.UP: + if floor > self.goal: + self.goal = floor + self.dropoffs.append(floor) + self.dropoffs.sort() + elif direction == Direction.DOWN: + if floor < self.goal: + self.goal = floor + self.dropoffs.append(floor) + self.dropoffs.sort(reverse=True) def __repr__(self): attrs = ', '.join('%s=%s' % t for t in self.__dict__.items()) @@ -25,7 +56,7 @@ class ElevatorControlSystem: self.pickup_requests.append((floor, direction)) def dropoff(self, elevator_id, floor): - self.elevators[elevator_id].goal = floor + self.elevators[elevator_id].dropoff(floor) def step(self): # serve pickup requests @@ -42,29 +73,33 @@ class ElevatorControlSystem: elevator.floor += 1 elif elevator.goal < elevator.floor: elevator.floor -= 1 - # check goal after moving + # check dropoffs and goal after moving + if elevator.dropoffs and elevator.dropoffs[0] == elevator.floor: + elevator.dropoffs = elevator.dropoffs[1:] if elevator.goal == elevator.floor: elevator.goal = None if __name__ == '__main__': ecs = ElevatorControlSystem(2) - print(ecs.elevators) + print(' '*4, ecs.elevators) print('requesting pickup on floor 2 down') ecs.pickup(2, Direction.DOWN) ecs.step() - print(ecs.elevators) + print(' '*4, ecs.elevators) print('requesting dropoff on floor 1 and pickup on floor 1 up') ecs.dropoff(0, 1) ecs.pickup(1, Direction.UP) ecs.step() - print(ecs.elevators) + print(' '*4, ecs.elevators) print('requesting dropoff on floor 3') ecs.dropoff(1, 3) ecs.step() - print(ecs.elevators) + print(' '*4, ecs.elevators) + print('requesting pickup on floor 2 up') + ecs.pickup(2, Direction.UP) ecs.step() - print(ecs.elevators) + print(' '*4, ecs.elevators) |