generated from public/aoc_template
65 lines
1.8 KiB
Python
65 lines
1.8 KiB
Python
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"),
|
|
(4766, "input5_martin"),
|
|
(5732, "input5"),
|
|
],
|
|
[
|
|
(123, "input5_test"),
|
|
(6257, "input5_martin"),
|
|
(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)
|