-
Notifications
You must be signed in to change notification settings - Fork 0
/
gatorDelivery.py
531 lines (455 loc) · 19.1 KB
/
gatorDelivery.py
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from AVL_unit import AVL_Tree, TreeNode
import argparse
import re
import sys
class Order(TreeNode):
def __init__(self, *args, **kwargs):
super(Order, self).__init__(*args, **kwargs)
class OrderManagementSystem(AVL_Tree):
def __init__(self):
super(OrderManagementSystem, self).__init__()
self.priority_tree = AVL_Tree() # 按优先级组织的AVL树
self.current_time = 0 # 系统当前时间,根据创建订单时更新
self.last_delivery_time = 0 # 记录上一个订单的送达时间
self.last_comeback = 0 # Last duration per trip, for comeback
self.order_count = 0
self.delivery_time = 0
self.return_time = 0
def create_order(self, order_id, current_system_time,
order_value, delivery_time):
# 更新系统时间和交付时间
self.current_time = current_system_time
self.delivery_time = delivery_time
order_delivered = self.get_delivered()
# 创建新订单
new_order = Order(order_id, current_system_time,
order_value, delivery_time)
order_list = self.inOrder(self.root)
if order_list is not None:
first_order = order_list[0]
if (new_order.priority > first_order.priority) and (
(first_order.ETA - first_order.delivery_time)
<= current_system_time):
first_order.priority = 100
# 将新订单插入到AVL树中
self.root = self.insert(self.root, new_order)
# 计算ETA
larger_node = self.get_near_large_node(self.root, order_id)
if not larger_node:# and self.order_count == 0: # first order
if self.return_time < current_system_time:
new_order.ETA = current_system_time + delivery_time
# if self.order_count == 0:
# self.return_time = current_system_time # 更新返回时间为当前系统时间
else:
new_order.ETA = self.return_time + delivery_time
else:
new_order.ETA = larger_node.ETA + larger_node.delivery_time\
+ new_order.delivery_time
# 更新最后一个订单的送达时间和返回时间
# self.last_delivery_time = new_order.ETA
# self.return_time = current_system_time \
# if self.return_time < current_system_time else self.return_time
# 打印ETA
print(f"Order {new_order.order_id} has been created - ETA: {new_order.ETA}")
self.order_count += 1
self.check_for_order_updates(new_order.order_id)
self.print_delivered(order_delivered)
# 检查是否有订单更新
def check_for_order_updates(self, order_id):
order_list = self.inOrder(self.root) # in descend priority order
if order_list is None:
return
index = 0
# find the index of order_id
for index, order in enumerate(order_list):
if order.order_id == order_id:
break
# 更新订单的预计送达时间
# update lower priority orders' ETA
updated_later_orders = []
for next_index in range(index + 1, len(order_list)):
order_list[next_index].ETA = order_list[next_index - 1].ETA + \
order_list[next_index - 1].delivery_time + \
order_list[next_index].delivery_time
updated_later_orders.append(order_list[next_index])
# 打印更新后的预计送达时间
if len(updated_later_orders) != 0:
s = "Updated ETAs: ["
for j, order in enumerate(updated_later_orders):
s += str(order.order_id) + ":" + str(order.ETA)
if j != len(updated_later_orders) - 1: # not last one
s += ","
s += "]"
print(s)
def cancel_order(self, order_id, current_system_time):
self.current_time = current_system_time
order_delivered = self.get_delivered()
order_list = self.inOrder(self.root)
found = False
key = 0
for key, order in enumerate(order_list):
if order.order_id == order_id:
found = True
break
if not found: # order not found
print(f"Cannot cancel. Order {order_id}"
f" has already been delivered.")
else:
# assume found
order_departure_moment = order_list[key].ETA -\
order_list[key].delivery_time
if order_departure_moment < current_system_time:
print(f"Cannot cancel. Order {order_id} is out for delivery.")
else:
updated_order = []
if key+1 == len(order_list):
pass
# if the cancelled order was the last order
# no other order need to be updated
elif key == 0:
# if the cancelled order was originally the next order
# and there are at least one order after canceling
sec_o = key + 1
# decided by the returning time of the delivery agent
# Become new first order
order_list[sec_o].ETA = self.return_time + \
order_list[sec_o].delivery_time
updated_order.append(order_list[sec_o])
# Update ETA of subsequent orders after second one
for i in range(sec_o + 1, len(order_list)):
order_list[i].ETA = order_list[i - 1].ETA + \
order_list[i - 1].delivery_time + \
order_list[i].delivery_time
updated_order.append(order_list[i])
else:
# if the cancelled order was not the first order (has order before and after it)
# Connect "the order before canceled one" with "the order after canceled one"
order_list[key+1].ETA = order_list[key-1].ETA + \
order_list[key-1].delivery_time + \
order_list[key+1].delivery_time
updated_order.append(order_list[key+1])
# Update ETA of subsequent orders after those two order
connect_two = key+1
for i in range(connect_two + 1, len(order_list)):
order_list[i].ETA = order_list[i - 1].ETA + \
order_list[i - 1].delivery_time + \
order_list[i].delivery_time
updated_order.append(order_list[i])
print(f"Order {order_id} has been canceled")
if len(updated_order) != 0:
s = "Updated ETAs: ["
for j, order in enumerate(updated_order):
s += str(order.order_id) + ":" + str(order.ETA)
if j != len(updated_order) - 1: # not last one
s += ","
s += "]"
print(s)
self.root = self.delete(self.root,
order_list[key].priority)
self.print_delivered(order_delivered)
def get_rank_of_order(self, order_id):
# Count how many orders before order_id
order_list = self.inOrder(self.root)
count = 0
for count, order in enumerate(order_list):
if order.order_id == order_id:
print(f"Order {order_id} will be delivered"
f" after {count} orders.")
break
return count
def update_time(self, order_id, current_system_time, new_delivery_time):
self.current_time = current_system_time
order_delivered = self.get_delivered()
order_list = self.inOrder(self.root)
found = False
key = 0
for key, order in enumerate(order_list):
if order.order_id == order_id:
found = True
break
if not found: # order not found
print(f"Cannot update. Order {order_id}"
f" has already been delivered.")
else:
order_departure_moment = order_list[key].ETA - \
order_list[key].delivery_time
if order_departure_moment <= current_system_time:
print(f"Cannot update. Order {order_id} is out for delivery.")
else:
dif = new_delivery_time - order_list[key].delivery_time
order_list[key].delivery_time = new_delivery_time
order_list[key].ETA += dif
for i in range(key+1, len(order_list)):
order_list[i].ETA += 2 * dif
s = "Updated ETAs: ["
while key < len(order_list):
s += str(order_list[key].order_id) + ":" \
+ str(order_list[key].ETA)
if key != len(order_list) - 1:
s += ","
key += 1
s += "]"
print(s)
self.print_delivered(order_delivered)
def print_trees(self):
print("\n==============================")
print(">>> Priority Tree:")
# print(self.priority_tree)
self.preOrder(self.root)
self.inOrder(self.root)
print()
self.printHelper(self.root, "", True)
print("==============================\n")
def print_within_time(self, **kwargs):
time1 = None
time2 = None
for key in kwargs:
if key == "order_id":
node_list = self.get_path(self.root, kwargs[key])
print(f"[{node_list[0].order_id},"
f" {node_list[0].current_system_time},"
f" {node_list[0].order_value},"
f" {node_list[0].delivery_time},"
f" {node_list[0].ETA}]")
return
if key == "time1":
time1 = kwargs[key]
if key == "time2":
time2 = kwargs[key]
# Print all orders that will be delivered within the period
order_list = self.inOrder(self.root)
result = []
if order_list is not None:
for order in order_list:
if time1 <= order.ETA <= time2:
result.append(order)
if len(result) == 0:
print("There are no orders in that time period")
else:
out = "["
for key, order in enumerate(result):
out += str(order.order_id)
if key != len(result) - 1: # not last one
out += ","
out += "]"
print(out)
def get_delivered(self):
# get the order that has been delivered
order_list = self.inOrder(self.root)
if order_list is None:
# nothing in tree
return
delivered_list = []
for order in order_list:
if order.ETA <= self.current_time:
delivered_list.append(order)
# self.last_delivery_time = order.ETA
# self.last_comeback = self.delivery_time
self.return_time = order.ETA + order.delivery_time
self.root = self.delete(self.root, order.priority)
else:
break
return delivered_list
def print_delivered(self, delivered_list=None):
# print the delivered order
if delivered_list is None:
return
# do nothing
else:
for order in delivered_list:
print(f"Order {order.order_id} has been delivered at time "
f"{order.ETA}")
def quit(self, tmp_list=None):
if tmp_list is None:
tmp_list = []
self.inOrder(self.root, tmp_list)
for order in range(len(tmp_list)):
print(f"Order {tmp_list[order].order_id} "
f"has been delivered at time {tmp_list[order].ETA}")
def delete(self, root, priority):
# Step 1 - Perform standard BST delete
if not root:
return root
elif priority < root.priority:
root.left = self.delete(root.left, priority)
elif priority > root.priority:
root.right = self.delete(root.right, priority)
else:
if root.left is None:
return root.right
if root.right is None:
return root.left
tmp_root = self.getMinValueNode(root.right)
root.priority = tmp_root.priority
root.order_id = tmp_root.order_id
root.current_system_time = tmp_root.current_system_time
root.order_value = tmp_root.order_value
root.delivery_time = tmp_root.delivery_time
root.ETA = tmp_root.ETA
root.right = self.delete(root.right,
tmp_root.priority)
# If the tree has only one node,
# simply return it
if root is None:
return root
# Step 2 - Update the height of the
# ancestor node
root.height = 1 + max(self.getHeight(root.left),
self.getHeight(root.right))
# Step 3 - Get the balance factor
balance = self.getBalance(root)
# Step 4 - If the node is unbalanced,
# then try out the 4 cases
# Case 1 - Left Left
if balance > 1 and self.getBalance(root.left) >= 0:
return self.rightRotate(root)
# Case 2 - Right Right
if balance < -1 and self.getBalance(root.right) <= 0:
return self.leftRotate(root)
# Case 3 - Left Right
if balance > 1 and self.getBalance(root.left) < 0:
root.left = self.leftRotate(root.left)
return self.rightRotate(root)
# Case 4 - Right Left
if balance < -1 and self.getBalance(root.right) > 0:
root.right = self.rightRotate(root.right)
return self.leftRotate(root)
return root
def _case():
# Example usage:
oms = OrderManagementSystem()
# Example 1
# oms.create_order(1001, 1, 200, 3)
# oms.create_order(1002, 3, 250, 6)
# oms.create_order(1003, 8, 100, 3)
# oms.create_order(1004, 13, 100, 5)
# oms.print_within_time(time1=2, time2=15)
# oms.update_time(1003, 15, 1)
# oms.create_order(1005, 30, 300, 3)
# oms.quit()
# Example 2
# oms.create_order(101, 2, 300, 4)
# oms.create_order(102, 3, 600, 3)
# oms.print_within_time(order_id=101)
# oms.create_order(103, 7, 200, 2)
# oms.create_order(104, 8, 500, 3)
# oms.cancel_order(102, 9)
# oms.create_order(105, 10, 300, 4)
# oms.get_rank_of_order(105)
# oms.quit()
# Testcase 1
# oms.create_order(1001, 1, 100, 4)
# oms.create_order(1002, 2, 150, 7)
# oms.create_order(1003, 8, 50, 2)
# oms.print_within_time(2, 15)
# oms.create_order(1004, 9, 300, 12)
# oms.get_rank_of_order(1004)
# oms.print_within_time(45, 55)
# oms.create_order(1005, 15, 400, 8)
# oms.create_order(1006, 17, 100, 3)
# oms.cancel_order(1005, 18)
# oms.get_rank_of_order(1004)
# oms.create_order(1007, 19, 600, 7)
# oms.create_order(1008, 25, 200, 8)
# oms.update_time(1007, 27, 12)
# oms.get_rank_of_order(1006)
# oms.print_within_time(55, 85)
# oms.create_order(1009, 36, 500, 15)
# oms.create_order(1010, 40, 250, 10)
# oms.quit()
# Testcase 3
# oms.create_order(4001, 1, 200, 3)
# oms.create_order(4002, 3, 250, 6)
# oms.create_order(4003, 8, 100, 3)
# oms.create_order(4004, 13, 100, 5)
# oms.print_within_time(time1=2, time2=15)
# oms.get_rank_of_order(4003)
# oms.update_time(4003, 15, 2)
# oms.create_order(4005, 17, 150, 4)
# oms.cancel_order(4002, 20)
# oms.create_order(4006, 22, 300, 3)
# oms.print_within_time(time1=10, time2=25)
# oms.create_order(4007, 25, 200, 2)
# oms.create_order(4008, 28, 350, 5)
# oms.print_within_time(time1=20, time2=30)
# oms.get_rank_of_order(4006)
# oms.create_order(4009, 32, 250, 3)
# oms.cancel_order(4004, 34)
# oms.update_time(4005, 37, 5)
# oms.create_order(4010, 40, 400, 6)
# oms.print_within_time(time1=35, time2=45)
# oms.get_rank_of_order(4007)
# oms.create_order(4011, 40, 200, 4)
# oms.create_order(4012, 42, 300, 3)
# oms.print_within_time(time1=50, time2=55)
# oms.update_time(4010, 55, 7)
# oms.cancel_order(4009, 56)
# oms.print_within_time(time1=60, time2=90)
# oms.quit()
# Testcase 2
# oms.create_order(3001, 1, 200, 7)
# oms.create_order(3002, 3, 250, 6)
# oms.create_order(3003, 8, 1000, 3)
# oms.create_order(3004, 13, 100, 5)
# oms.create_order(3005, 15, 300, 4)
# oms.create_order(3006, 17, 800, 2)
# oms.print_within_time(time1=2, time2=20)
# oms.update_time(3004, 20, 2)
# oms.print_within_time(time1=5, time2=25)
# oms.cancel_order(3005, 25)
# oms.print_within_time(time1=10, time2=30)
# oms.create_order(3007, 30, 200, 3)
# oms.get_rank_of_order(3005)
# oms.create_order(3008, 33, 250, 6)
# oms.create_order(3009, 38, 100, 3)
# oms.create_order(3010, 40, 4000, 5)
# oms.get_rank_of_order(3008)
# oms.create_order(3011, 45, 300, 4)
# oms.create_order(3012, 47, 150, 2)
# oms.print_within_time(time1=35, time2=50)
# oms.get_rank_of_order(3006)
# oms.quit()
def read_file(file_path):
with open(file_path, 'r') as file:
content = file.readlines()
return content
def _extract_numbers(text: str):
numbers = re.findall(r'\d+', text)
return list(map(int, numbers))
def content_switch(content: list):
oms = OrderManagementSystem()
for line in content:
line = line.lower()
args = _extract_numbers(line)
if "createorder" in line:
oms.create_order(args[0], args[1], args[2], args[3])
elif "print" in line and len(args) == 2:
oms.print_within_time(time1=args[0], time2=args[1])
elif "print" in line and len(args) == 1:
oms.print_within_time(order_id=args[0])
elif "getrankoforder" in line:
oms.get_rank_of_order(args[0])
elif "cancelorder" in line:
oms.cancel_order(args[0], args[1])
elif "updatetime" in line:
oms.update_time(args[0], args[1], args[2])
elif "quit" in line:
oms.quit()
else:
print(f"Function not found: {line}")
exit(1)
def main():
parser = argparse.ArgumentParser(
description='Read contents of a text file.')
parser.add_argument('file', metavar='FILE',
type=str, help='Path to the text file')
args = parser.parse_args()
file_content = read_file(args.file)
output_file = f"{args.file[:-4]}_output_file.txt"
with open(output_file, 'w') as sys.stdout:
content_switch(file_content)
if __name__ == "__main__":
main()
# _case()