aoc2020/day09.py
Stefan Harmuth 76d238fc7b day 9
2020-12-09 06:21:48 +01:00

56 lines
1.4 KiB
Python

import aoclib
import itertools
DAY = 9
TEST_SOLUTION_PART1 = 127
TEST_SOLUTION_PART2 = 62
class NumberCruncher:
def __init__(self, preamble):
self.buffer = []
self.preamble = preamble
def addNumber(self, number):
self.buffer.append(number)
if len(self.buffer) > self.preamble:
self.buffer = self.buffer[1:]
def isValidNextNumber(self, number):
if len(self.buffer) < self.preamble:
return True
for combination in itertools.combinations(self.buffer, 2):
if sum(combination) == number:
return True
return False
def part1(test_mode=False):
my_input = aoclib.getInputAsArray(day=DAY, return_type=int, test=test_mode)
if test_mode:
cruncher = NumberCruncher(5)
else:
cruncher = NumberCruncher(25)
for i in my_input:
if not cruncher.isValidNextNumber(i):
return i
cruncher.addNumber(i)
return 0
def part2(test_mode=False):
my_input = aoclib.getInputAsArray(day=DAY, return_type=int, test=test_mode)
sum_to_find = part1(test_mode)
for start_index in range(0, len(my_input)):
for stop_index in range(start_index + 1, len(my_input) - start_index - 1):
if sum(my_input[start_index:stop_index]) == sum_to_find:
return min(my_input[start_index:stop_index]) + max(my_input[start_index:stop_index])
return 0