Solve day 7 and 8 of 2018.

This commit is contained in:
2024-07-07 20:25:04 -04:00
parent 9df26ebe71
commit da1c37ffa7
3 changed files with 124 additions and 4 deletions

View File

@@ -1,12 +1,71 @@
from lib import str_to_ints
from lib import LETTERS_UPPER
def part_1(data):
print(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):
pass
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():

59
2018/d8.py Normal file
View File

@@ -0,0 +1,59 @@
from lib import *
def parse(fields, i):
n_children = fields[i]
n_meta = fields[i + 1]
i += 2
children = []
meta_score = 0
for _ in range(n_children):
c, i, m = parse(fields, i)
children.append(c)
meta_score += m
for i in range(i, i + n_meta):
meta_score += fields[i]
i += 1
return children, i, meta_score
def parse2(fields, i):
n_children = fields[i]
n_meta = fields[i + 1]
i += 2
children = []
scores = []
for _ in range(n_children):
c, i, s = parse2(fields, i)
children.append(c)
scores.append(s)
score = 0
if n_children == 0:
for j in range(i, i + n_meta):
score += fields[j]
else:
for j in range(i, i + n_meta):
new_i = fields[j]
new_i -= 1
if new_i < 0:
continue
if new_i < len(children):
score += scores[new_i]
i += n_meta
return children, i, score
def main():
input_file = __file__.replace(".py", ".txt")
with open(input_file) as f:
data = f.read()
nums = str_to_ints(data)
tree = parse(nums, 0)
print(tree[2])
tree = parse2(nums, 0)
print(tree[2])
if __name__ == "__main__":
main()