This commit is contained in:
Stefan Harmuth 2024-12-05 07:06:45 +01:00
parent c4c5f691be
commit 5796d65b3d
3 changed files with 1459 additions and 0 deletions

62
day05.py Normal file
View File

@ -0,0 +1,62 @@
from tools.aoc import AOCDay
from typing import Any
def is_update_valid(rules: list[list[int]], update: list[int]) -> bool:
for rule in rules:
if rule[0] in update and rule[1] in update and update.index(rule[0]) > update.index(rule[1]):
return False
return True
class Day(AOCDay):
inputs = [
[
(143, "input5_test"),
(5732, "input5"),
],
[
(123, "input5_test"),
(4716, "input5"),
],
]
def parse_input(self) -> tuple[list[list[int]], list[list[int]]]:
rules, pages = self.getMultiLineInputAsArray()
rule_list = [list(map(int, s.split("|"))) for s in rules]
update_list = [list(map(int, s.split(","))) for s in pages]
return rule_list, update_list
def part1(self) -> Any:
rules, updates = self.parse_input()
ans = 0
for update in updates:
if is_update_valid(rules, update):
ans += update[len(update) // 2]
return ans
def part2(self) -> Any:
rules, updates = self.parse_input()
ans = 0
for update in updates:
if is_update_valid(rules, update):
continue
while not is_update_valid(rules, update):
for rule in rules:
if rule[0] in update and rule[1] in update and update.index(rule[0]) > update.index(rule[1]):
a, b = update.index(rule[0]), update.index(rule[1])
update[a], update[b] = update[b], update[a]
ans += update[len(update) // 2]
return ans
if __name__ == "__main__":
day = Day(2024, 5)
day.run(verbose=True)

1369
inputs/input5 Normal file

File diff suppressed because it is too large Load Diff

28
inputs/input5_test Normal file
View File

@ -0,0 +1,28 @@
47|53
97|13
97|61
97|47
75|29
61|13
75|53
29|13
97|29
53|29
61|53
97|53
61|29
47|13
75|47
97|75
47|61
75|61
47|29
75|13
53|13
75,47,61,53,29
97,61,53,29,13
75,29,13
75,97,47,61,53
61,13,29
97,13,75,29,47