-
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Signed-off-by: GitHub <[email protected]>
- Loading branch information
1 parent
a8bdc82
commit 8d870cc
Showing
2 changed files
with
51 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,31 @@ | ||
from collections import Counter | ||
from pathlib import Path | ||
|
||
|
||
def parse_input(text: str) -> tuple[list[int], list[int]]: | ||
rows = text.strip().split("\n") | ||
|
||
left = [] | ||
right = [] | ||
for row in rows: | ||
left_str, right_str = row.split() | ||
left.append(int(left_str)) | ||
right.append(int(right_str)) | ||
left.sort() | ||
right.sort() | ||
return left, right | ||
|
||
|
||
def part1(left: list[int], right: list[int]) -> int: | ||
return sum(abs(left[index] - right[index]) for index in range(len(left))) | ||
|
||
|
||
def part2(left: list[int], right: list[int]) -> int: | ||
right_counter = Counter(right) | ||
return sum(left_number * right_counter[left_number] for left_number in left) | ||
|
||
|
||
if __name__ == "__main__": | ||
rows = Path("../input.txt").read_text(encoding="locale") | ||
print(part1(*parse_input(rows))) | ||
print(part2(*parse_input(rows))) |
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,20 @@ | ||
import pytest | ||
from aoc_2024_01 import parse_input, part1, part2 | ||
|
||
TEST_INPUT = """ | ||
3 4 | ||
4 3 | ||
2 5 | ||
1 3 | ||
3 9 | ||
3 3 | ||
""" | ||
|
||
def test_parse_input() -> None: | ||
assert parse_input(TEST_INPUT) == ([1, 2, 3, 3, 3, 4], [3, 3, 3, 4, 5, 9]) | ||
|
||
def test_part1() -> None: | ||
assert part1(*parse_input(TEST_INPUT)) == 11 | ||
|
||
def test_part2() -> None: | ||
assert part2(*parse_input(TEST_INPUT)) == 31 |