aocpy/2018/d7.py

81 lines
1.9 KiB
Python

from lib import LETTERS_UPPER
def part_1(data):
deps = {c: [] for c in LETTERS_UPPER}
for line in data.splitlines():
fields = line.split()
a, b = fields[1], fields[7]
deps[b].append(a)
ready = []
for x, ys in deps.items():
if len(ys) == 0:
ready.append(x)
seq = []
ready = sorted(ready)
while ready:
current, ready = ready[0], ready[1:]
seq.append(current)
for x, ys in deps.items():
if current in ys:
ys.remove(current)
if len(ys) == 0:
ready.append(x)
ready = sorted(ready)
print("".join(seq))
def score(c):
return 1 + ord(c) - ord("A") + 60
def part_2(data):
deps = {c: [] for c in LETTERS_UPPER}
for line in data.splitlines():
fields = line.split()
a, b = fields[1], fields[7]
deps[b].append(a)
ready = []
done = []
for x, ys in deps.items():
if len(ys) == 0:
ready.append(x)
workers = {}
steps = 0
while len(done) != 26:
ready = sorted(ready)
while len(ready) > 0 and len(workers) < 5:
current, ready = ready[0], ready[1:]
workers[current] = score(current)
to_del = []
for k in workers.keys():
workers[k] -= 1
if workers[k] == 0:
to_del.append(k)
done.append(k)
for x, ys in deps.items():
if k in ys:
ys.remove(k)
if len(ys) == 0:
ready.append(x)
for k in to_del:
del workers[k]
steps += 1
print(steps)
def main():
input_file = __file__.replace(".py", ".txt")
with open(input_file) as f:
data = f.read()
part_1(data)
part_2(data)
if __name__ == "__main__":
main()