Implement day 1 solver
This commit is contained in:
33
puzzles/1.py
Normal file
33
puzzles/1.py
Normal file
@@ -0,0 +1,33 @@
|
||||
from collections import Counter
|
||||
|
||||
test_input = """
|
||||
3 4
|
||||
4 3
|
||||
2 5
|
||||
1 3
|
||||
3 9
|
||||
3 3
|
||||
""".strip()
|
||||
|
||||
test_solution_p1 = 11
|
||||
test_solution_p2 = 31
|
||||
|
||||
|
||||
def solve_p1(puzzle_input: str) -> int:
|
||||
list1, list2 = _parse_lists(puzzle_input)
|
||||
pairs = zip(sorted(list1), sorted(list2))
|
||||
distances = (abs(pair[0] - pair[1]) for pair in pairs)
|
||||
return sum(distances)
|
||||
|
||||
|
||||
def solve_p2(puzzle_input: str) -> int:
|
||||
list1, list2 = _parse_lists(puzzle_input)
|
||||
occurrences = Counter(list2)
|
||||
similarities = (value * occurrences.get(value, 0) for value in list1)
|
||||
return sum(similarities)
|
||||
|
||||
|
||||
def _parse_lists(puzzle_input: str) -> tuple[list[int], list[int]]:
|
||||
lines = (line.partition(" ") for line in puzzle_input.split("\n") if line)
|
||||
list1, list2 = zip(*((int(line[0]), int(line[2])) for line in lines))
|
||||
return list1, list2
|
Reference in New Issue
Block a user