mirror of
https://github.com/thib8956/advent-of-code.git
synced 2024-12-25 21:36:29 +00:00
2024 day 5 part 2
This commit is contained in:
parent
5fb0e1523c
commit
b8c01cc245
@ -7,25 +7,39 @@ def check_update(upd, rules):
|
|||||||
if [a, b] not in rules:
|
if [a, b] not in rules:
|
||||||
return False
|
return False
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def fix_update(upd, rules):
|
||||||
|
while not check_update(upd, rules):
|
||||||
|
for i in range(len(upd)):
|
||||||
|
for j in range(i+1, len(upd)):
|
||||||
|
if [upd[j], upd[i]] in rules:
|
||||||
|
upd[j], upd[i] = upd[i], upd[j]
|
||||||
|
|
||||||
def main(content):
|
def main(content):
|
||||||
order, updates = content.split("\n\n")
|
rules, updates = content.split("\n\n")
|
||||||
order = [x.split("|") for x in order.split("\n")]
|
rules = [x.split("|") for x in rules.split("\n")]
|
||||||
updates = [x.split(",") for x in updates.rstrip().split("\n")]
|
updates = [x.split(",") for x in updates.rstrip().split("\n")]
|
||||||
|
|
||||||
part1 = 0
|
part1 = 0
|
||||||
|
incorrect_updates = []
|
||||||
for update in updates:
|
for update in updates:
|
||||||
if check_update(update, order):
|
if check_update(update, rules):
|
||||||
middle = update[len(update)//2]
|
middle = update[len(update)//2]
|
||||||
part1 += int(middle)
|
part1 += int(middle)
|
||||||
|
else:
|
||||||
|
incorrect_updates.append(update)
|
||||||
print("Part 1: ", part1)
|
print("Part 1: ", part1)
|
||||||
|
|
||||||
|
part2 = 0
|
||||||
|
for update in incorrect_updates:
|
||||||
|
fix_update(update, rules)
|
||||||
|
middle = update[len(update)//2]
|
||||||
|
part2 += int(middle)
|
||||||
|
print("Part 2: ", part2)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
import sys
|
import sys
|
||||||
infile = sys.argv[1] if 1 < len(sys.argv) else "example.txt"
|
infile = sys.argv[1] if 1 < len(sys.argv) else "example.txt"
|
||||||
with open(infile) as f:
|
with open(infile) as f:
|
||||||
main(f.read())
|
main(f.read())
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user