Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Advent of Code 2024 - Day 5 : Python version #46

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions advent_of_code/2024(python)/day5.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@

from collections import defaultdict

def solve_day5_part1(rules:list[str], pages:list[str])->int:
before_rules = defaultdict(list)
for rule in rules:
first, second = rule.split("|")
# each item stores what item must be before current one
# before the rule : 75 : [97]
# after the rule : 97 : [75]
before_rules[int(second)].append(int(first))

res = 0
for page in pages:
nums = [int(num) for num in page.split(",")]
is_ok = True
for i in range(1, len(nums)):
for j in range(i):
# check whether it fits with the rule
first_num, second_num = nums[j], nums[i]
if second_num in before_rules[first_num]:
is_ok = False
break
if not is_ok:
break

if is_ok:
res += nums[len(nums)//2-1 if len(nums)%2==0 else len(nums)//2]

return res
Loading
Loading