solve day 5 part 1
This commit is contained in:
parent
0f8c9c22be
commit
965aba2b21
1 changed files with 40 additions and 2 deletions
|
|
@ -7,9 +7,47 @@ def get_lines(filename: str) -> list:
|
||||||
return [line.strip() for line in file.readlines()]
|
return [line.strip() for line in file.readlines()]
|
||||||
|
|
||||||
|
|
||||||
|
def get_rules_and_updates(lines: list) -> tuple:
|
||||||
|
rules = {}
|
||||||
|
updates = []
|
||||||
|
for line in lines:
|
||||||
|
if "|" in line:
|
||||||
|
a, b = line.split("|")
|
||||||
|
if rules.get(b):
|
||||||
|
rules[b].append(a)
|
||||||
|
else:
|
||||||
|
rules[b] = [a]
|
||||||
|
elif "," in line:
|
||||||
|
updates.append(line.split(","))
|
||||||
|
return rules, updates
|
||||||
|
|
||||||
|
|
||||||
|
def check_validity(rules: dict, update: list) -> bool:
|
||||||
|
for position, page_number in enumerate(update):
|
||||||
|
if page_number not in rules:
|
||||||
|
continue
|
||||||
|
# if a number that is supposed to come earlier than our current page_number
|
||||||
|
# is included in the rest of the update, it breaks the rules
|
||||||
|
for earlier_number in rules[page_number]:
|
||||||
|
if earlier_number in update[position:]:
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def get_middle_page_sums(rules: dict, updates: list) -> int:
|
||||||
|
middle_page_sum = 0
|
||||||
|
for update in updates:
|
||||||
|
if check_validity(rules, update):
|
||||||
|
middle_page_sum += int(update[int(len(update) / 2)])
|
||||||
|
return middle_page_sum
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
lines = get_lines("sample-input.txt")
|
# lines = get_lines("sample-input.txt")
|
||||||
# lines = get_lines("input.txt")
|
lines = get_lines("input.txt")
|
||||||
|
|
||||||
|
rules, updates = get_rules_and_updates(lines)
|
||||||
|
print("Part 1: The sum of valid middle pages is:", get_middle_page_sums(rules, updates))
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue