Compare commits

..

2 commits

Author SHA1 Message Date
2992dd60b2 Add day 7B 2018-12-07 10:55:39 +01:00
829128a5be Day 7a 2018-12-07 08:07:03 +01:00
2 changed files with 114 additions and 0 deletions

32
Day7/Day7A.py Normal file
View file

@ -0,0 +1,32 @@
import fileinput
from collections import defaultdict
def build_graph():
graph = defaultdict(list)
for line in fileinput.input():
a, b = line[5], line[36]
graph[b].append(a)
graph[a]
return graph
def main():
graph = build_graph()
order = []
to_consider = sorted(graph.keys())
while to_consider:
for i, node in enumerate(to_consider):
parents = graph[node]
if any(parent in to_consider for parent in parents):
continue
order.append(node)
del to_consider[i]
break
print("".join(order))
if __name__ == "__main__":
main()

82
Day7/Day7B.py Normal file
View file

@ -0,0 +1,82 @@
import fileinput
from collections import defaultdict
from Day7A import build_graph
WORKERS = 5
BASE_TIME = 60
graph = build_graph()
order = []
to_consider = sorted(graph.keys())
worker_nodes = [None] * WORKERS
worker_times = [None] * WORKERS
active_workers = 0
time = 0
def work_seconds(node):
return ord(node) - ord('A') + BASE_TIME
def start_work(worker, node):
global active_workers
worker_nodes[worker] = node
worker_times[worker] = work_seconds(node)
active_workers += 1
def update_workers():
global time
global active_workers
for i in range(WORKERS):
if worker_nodes[i] is None:
continue
if worker_times[i]:
worker_times[i] -= 1
else:
active_workers -= 1
worker_nodes[i] = None
time += 1
def print_status():
worker_status = "".join(node if node else "." for node in worker_nodes)
todo = "".join(to_consider)
print(f"{time:>4d} {worker_status:<7} [{todo}]")
def main():
global active_workers
print("Time Workers To Do")
while to_consider or active_workers:
last_count = -1
while last_count != active_workers:
last_count = active_workers
for i, node in enumerate(to_consider):
parents = graph[node]
if node in worker_nodes:
continue
if any(parent in worker_nodes or parent in to_consider
for parent in parents):
continue
for w_id in range(WORKERS):
if worker_nodes[w_id] is None:
start_work(w_id, node)
break
else:
break
del to_consider[i]
continue
print_status()
update_workers()
print_status()
main()