|
| 1 | +import sys |
| 2 | +import random |
| 3 | +import collections |
| 4 | +import queue |
| 5 | + |
| 6 | +Event = collections.namedtuple('Event', 'time actor description') |
| 7 | + |
| 8 | +FIND_CUSTOMER_INTERVAL = 4 |
| 9 | +TRIP_DURATION = 10 |
| 10 | + |
| 11 | + |
| 12 | +def compute_delay(interval): |
| 13 | + return int(random.expovariate(1/interval)) |
| 14 | + |
| 15 | + |
| 16 | +def taxi_process(sim, ident): |
| 17 | + trips = 3 |
| 18 | + for i in range(trips): |
| 19 | + prowling_time = compute_delay(FIND_CUSTOMER_INTERVAL) |
| 20 | + yield Event(sim.time + prowling_time, ident, 'customer picked up') |
| 21 | + |
| 22 | + trip_time = compute_delay(TRIP_DURATION) |
| 23 | + yield Event(sim.time + trip_time, ident, 'customer dropped off') |
| 24 | + |
| 25 | + |
| 26 | +class Simulator: |
| 27 | + |
| 28 | + def __init__(self): |
| 29 | + self.events = queue.PriorityQueue() |
| 30 | + self.time = 0 |
| 31 | + |
| 32 | + def run(self, end_time): |
| 33 | + taxis = [taxi_process(self, i) for i in range(3)] |
| 34 | + while self.time < end_time: |
| 35 | + for index, taxi in enumerate(taxis): |
| 36 | + try: |
| 37 | + future_event = next(taxi) |
| 38 | + except StopIteration: |
| 39 | + del taxis[index] # remove taxi not in service |
| 40 | + else: |
| 41 | + self.events.put(future_event) |
| 42 | + if self.events.empty(): |
| 43 | + print('*** end of events ***') |
| 44 | + break |
| 45 | + event = self.events.get() |
| 46 | + self.time = event.time |
| 47 | + print('taxi:', event.actor, event) |
| 48 | + else: |
| 49 | + print('*** end of simulation time ***') |
| 50 | + |
| 51 | + |
| 52 | +def main(args): |
| 53 | + if args: |
| 54 | + end_time = int(args[0]) |
| 55 | + else: |
| 56 | + end_time = 10 |
| 57 | + sim = Simulator() |
| 58 | + sim.run(end_time) |
| 59 | + |
| 60 | +if __name__ == '__main__': |
| 61 | + main(sys.argv[1:]) |
0 commit comments