Skip to content

Instantly share code, notes, and snippets.

@lovetheguitar
Created December 1, 2024 18:33
Show Gist options
  • Save lovetheguitar/fcf82a8281217dcc7943af27fa91cac9 to your computer and use it in GitHub Desktop.
Save lovetheguitar/fcf82a8281217dcc7943af27fa91cac9 to your computer and use it in GitHub Desktop.
Advent of code - day 1 python
import collections
import pathlib
def get_sorted_lists_from_input(input_file_path: pathlib.Path) -> tuple[list[int], list[int]]:
input_lines = input_file_path.read_text().split("\n")
list_one = []
list_two = []
for line in input_lines:
if line:
value_one, value_two = line.split()
list_one.append(int(value_one))
list_two.append((int(value_two)))
sorted_list_one = sorted(list_one)
sorted_list_two = sorted(list_two)
return sorted_list_one, sorted_list_two
def calculate_total_distance(input_file_path: pathlib.Path) -> int:
sorted_list_one, sorted_list_two = get_sorted_lists_from_input(input_file_path)
total_distance = 0
for value_one, value_two in zip(sorted_list_one, sorted_list_two):
distance = abs(value_one - value_two)
total_distance += distance
return total_distance
def calculate_similarity_score(input_file_path: pathlib.Path) -> int:
sorted_list_one, sorted_list_two = get_sorted_lists_from_input(input_file_path)
counter_of_list_two = collections.Counter(sorted_list_two)
similarity_score = 0
for value_one in sorted_list_one:
number_of_times_in_list_two = counter_of_list_two.get(value_one, 0)
similarity_score += value_one * number_of_times_in_list_two
return similarity_score
def main():
input_file_path = pathlib.Path("input.txt")
print(f"{calculate_total_distance(input_file_path)=}")
print(f"f{calculate_similarity_score(input_file_path)=}")
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment