-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
daf2e4a
commit 7c0998f
Showing
2 changed files
with
58 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |