Skip to content

Commit 9918b9a

Browse files
feat: add 2024 day 1 part 1 & 2
1 parent 7e95e3e commit 9918b9a

File tree

4 files changed

+75
-0
lines changed

4 files changed

+75
-0
lines changed

src/adventofcode/year_2024/__init__.py

Whitespace-only changes.
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
from collections import Counter
2+
3+
from adventofcode.registry.decorators import register_solution
4+
from adventofcode.util.exceptions import SolutionNotFoundError
5+
from adventofcode.util.input_helpers import get_input_for_day
6+
7+
8+
def parse_input(input_data: list[str]) -> tuple[list, list]:
9+
left_list: list[int] = []
10+
right_list: list[int] = []
11+
12+
for row in input_data:
13+
left, right = row.split(" ")
14+
left_list.append(int(left))
15+
right_list.append(int(right))
16+
17+
return sorted(left_list), sorted(right_list)
18+
19+
20+
def calculate_distances(data: tuple[list[int], list[int]]) -> int:
21+
total = 0
22+
for left, right in zip(*data, strict=True):
23+
total += abs(left - right)
24+
25+
return total
26+
27+
28+
def calculate_similarity(data: tuple[list[int], list[int]]) -> int:
29+
total = 0
30+
left_list, right_list = data
31+
right_counter = Counter(right_list)
32+
33+
for num in left_list:
34+
total += right_counter[num] * num
35+
36+
return total
37+
38+
39+
@register_solution(2024, 1, 1)
40+
def part_one(input_data: list[str]):
41+
parsed_input = parse_input(input_data)
42+
answer = calculate_distances(parsed_input)
43+
44+
if not answer:
45+
raise SolutionNotFoundError(2024, 1, 1)
46+
47+
return answer
48+
49+
50+
@register_solution(2024, 1, 2)
51+
def part_two(input_data: list[str]):
52+
parsed_input = parse_input(input_data)
53+
answer = calculate_similarity(parsed_input)
54+
55+
if not answer:
56+
raise SolutionNotFoundError(2024, 1, 2)
57+
58+
return answer
59+
60+
61+
if __name__ == "__main__":
62+
data = get_input_for_day(2024, 1)
63+
part_one(data)
64+
part_two(data)

tests/adventofcode/year_2024/__init__.py

Whitespace-only changes.
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
from adventofcode.year_2024.day_01_2024 import part_one, part_two
2+
3+
test_input = ["3 4", "4 3", "2 5", "1 3", "3 9", "3 3"]
4+
5+
6+
def test_part_one():
7+
assert part_one(test_input) == 11
8+
9+
10+
def test_part_two():
11+
assert part_two(test_input) == 31

0 commit comments

Comments
 (0)