Skip to content

Commit

Permalink
2024 day 5
Browse files Browse the repository at this point in the history
  • Loading branch information
Spacerulerwill committed Jan 7, 2025
1 parent daf2e4a commit 7c0998f
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 0 deletions.
26 changes: 26 additions & 0 deletions puzzles/Y2024/D5/p1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
from typing import Any
from collections import defaultdict


def puzzle(input: str) -> Any:
s = input.split("\n\n")
rules = [list(map(int, rule.split("|"))) for rule in s[0].strip().splitlines()]
updates = [
list(map(int, update.split(","))) for update in s[1].strip().splitlines()
]

# map of every number to the set of every number it must come before
before = defaultdict(set)
for rule in rules:
before[rule[0]].add(rule[1])

sum = 0
for update in updates:
seen: set[int] = set()
for num in update:
if len(seen.intersection(before[num])) != 0:
break
seen.add(num)
else:
sum += update[len(update) // 2]
return sum
32 changes: 32 additions & 0 deletions puzzles/Y2024/D5/p2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
from typing import Any
from collections import defaultdict
from functools import cmp_to_key


def puzzle(input: str) -> Any:
s = input.split("\n\n")
rules = [list(map(int, rule.split("|"))) for rule in s[0].strip().splitlines()]
updates = [
list(map(int, update.split(","))) for update in s[1].strip().splitlines()
]

# map of every number to the set of every number it must come before
before = defaultdict(set)
for rule in rules:
before[rule[0]].add(rule[1])

def compare(a: int, b: int) -> int:
if b in before[a]:
return -1
return 0

sum = 0
for update in updates:
seen: set[int] = set()
for num in update:
if len(seen.intersection(before[num])) != 0:
update.sort(key=cmp_to_key(compare))
sum += update[len(update) // 2]
break
seen.add(num)
return sum

0 comments on commit 7c0998f

Please sign in to comment.