Advertisement
bob_f

AOC2020D09.py

Oct 1st, 2024 (edited)
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.51 KB | None | 0 0
  1. from itertools import combinations
  2.  
  3. def get_puzzle_input(a_file_name: str) -> list[int]:
  4.     with open(a_file_name) as INFILE:
  5.         return [int(line) for line in INFILE]
  6.  
  7. def solve_p1(a_numbers: list[int], a_rolling_window_length: int) -> int:
  8.     current_index = a_rolling_window_length
  9.    
  10.     while True:
  11.         sum_matches_number: bool = False
  12.    
  13.         for combo in combinations(numbers[current_index - a_rolling_window_length:current_index], 2):
  14.             if combo[0] + combo[1] == numbers[current_index]:
  15.                 sum_matches_number = True
  16.                 break
  17.    
  18.         if sum_matches_number:
  19.             current_index += 1
  20.         else:
  21.             return numbers[current_index]
  22.  
  23. def solve_p2(a_numbers: list[int], a_target: int) -> tuple[int, int]:
  24.     start_index: int = 0
  25.     current_index: int = start_index
  26.     candidate_numbers: list[int] = []
  27.  
  28.     while True:
  29.         candidate_numbers.append(a_numbers[current_index])
  30.  
  31.         if sum(candidate_numbers) == a_target:
  32.             break
  33.         elif sum(candidate_numbers) > a_target:
  34.             start_index += 1
  35.             current_index = start_index
  36.             candidate_numbers = []
  37.             continue
  38.         else:
  39.             current_index += 1
  40.  
  41.     return min(candidate_numbers), max(candidate_numbers)
  42.  
  43. numbers = get_puzzle_input('aoc_2020/aoc_2020_day_09.txt')
  44. # print(f"{numbers=}")
  45.  
  46. p1: int = solve_p1(numbers, 25)
  47. print(f"{p1=}")
  48.  
  49. p2_lo, p2_hi = solve_p2(numbers, p1)
  50. print(f"p2={p2_lo + p2_hi}")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement