day5 part2

This commit is contained in:
Tyrel Souza 2024-12-05 02:11:14 -05:00
parent 30de9566c5
commit 9aa022a75f

View File

@ -14,30 +14,53 @@ def read(rows):
rules.append(list(map(int, row.split("|")))) rules.append(list(map(int, row.split("|"))))
return rules, updates return rules, updates
def get_bads(rules, updates):
# @shared.profile bads = []
def part1(rows):
rules, updates = read(rows)
bad = []
for idx, update in enumerate(updates): for idx, update in enumerate(updates):
for first, second in rules: for first, second in rules:
if first in update and second in update: if first in update and second in update:
first_idx = update.index(first) first_idx = update.index(first)
second_idx = update.index(second) second_idx = update.index(second)
if first_idx > second_idx: if first_idx > second_idx:
bad.append(idx) bads.append(idx)
break break
return bads
# @shared.profile
def part1(rows):
rules, updates = read(rows)
bads = get_bads(rules, updates)
total = 0 total = 0
for idx, update in enumerate(updates): for idx, update in enumerate(updates):
if idx in bad: if idx in bads:
continue continue
total += update[len(update) // 2] total += update[len(update) // 2]
print(total) print(total)
def fix_bad(rules, bad):
for first, second in rules:
if first in bad and second in bad:
first_idx = bad.index(first)
second_idx = bad.index(second)
if first_idx > second_idx:
bad[first_idx], bad[second_idx] = bad[second_idx], bad[first_idx]
return bad
# @shared.profile # @shared.profile
def part2(rows): def part2(rows):
pass rules, updates = read(rows)
bads = get_bads(rules, updates)
total = 0
for idx in bads:
bad = updates[idx]
while True:
after = fix_bad(rules, bad[:])
if bad == after:
break
bad = after
total += bad[len(bad) // 2]
print(total)
def main(): def main():
rows = [row for row in shared.load_rows(5)] rows = [row for row in shared.load_rows(5)]