47 lines
1.3 KiB
Python
Executable file
47 lines
1.3 KiB
Python
Executable file
#!/usr/bin/env python3
|
|
|
|
# https://adventofcode.com/2024/day/1
|
|
|
|
def get_lines(filename: str) -> list:
|
|
with open(filename, "r") as file:
|
|
return [line.strip() for line in file.readlines()]
|
|
|
|
|
|
def get_lists(lines: list) -> (list, list):
|
|
list_a = []
|
|
list_b = []
|
|
for line in lines:
|
|
(a, b) = line.split()
|
|
list_a.append(int(a))
|
|
list_b.append(int(b))
|
|
return list_a, list_b
|
|
|
|
|
|
def get_total_distance(list_a: list, list_b: list) -> int:
|
|
total_distance = 0
|
|
sorted_a = sorted(list_a)
|
|
sorted_b = sorted(list_b)
|
|
for a, b in zip(sorted_a, sorted_b):
|
|
total_distance += abs(b - a)
|
|
return total_distance
|
|
|
|
|
|
def get_similarity_score(list_a: list, list_b: list) -> int:
|
|
similarity_score = 0
|
|
for search_val in list_a:
|
|
# returns list of positions where search_val was found
|
|
appearances = [i for i, x in enumerate(list_b) if x == search_val]
|
|
similarity_score += search_val * len(appearances)
|
|
return similarity_score
|
|
|
|
|
|
def main():
|
|
# lines = get_lines("sample-input.txt")
|
|
lines = get_lines("input.txt")
|
|
list_a, list_b = get_lists(lines)
|
|
print("Part 1: Total distance is", get_total_distance(list_a, list_b))
|
|
print("Part 2: Similarity score is", get_similarity_score(list_a, list_b))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|