|
| 1 | +# MIT License |
| 2 | +# |
| 3 | +# Copyright (c) 2020 Andrew Krepps |
| 4 | +# |
| 5 | +# Permission is hereby granted, free of charge, to any person obtaining a copy |
| 6 | +# of this software and associated documentation files (the "Software"), to deal |
| 7 | +# in the Software without restriction, including without limitation the rights |
| 8 | +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 9 | +# copies of the Software, and to permit persons to whom the Software is |
| 10 | +# furnished to do so, subject to the following conditions: |
| 11 | +# |
| 12 | +# The above copyright notice and this permission notice shall be included in all |
| 13 | +# copies or substantial portions of the Software. |
| 14 | +# |
| 15 | +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 16 | +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 17 | +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 18 | +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 19 | +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 20 | +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
| 21 | +# SOFTWARE. |
| 22 | + |
| 23 | + |
| 24 | +from . import day1 |
| 25 | +from . import util |
| 26 | + |
| 27 | + |
| 28 | +def find_invalid_number(numbers, preamble_length): |
| 29 | + for idx in range(preamble_length, len(numbers)): |
| 30 | + num = numbers[idx] |
| 31 | + if day1.find_sum_pair(numbers[idx - preamble_length:idx], num) is None: |
| 32 | + return num |
| 33 | + return None |
| 34 | + |
| 35 | + |
| 36 | +def find_contiguous_sum(numbers, target): |
| 37 | + for length in range(2, len(numbers)): |
| 38 | + for idx in range(len(numbers) - length + 1): |
| 39 | + contiguous_range = numbers[idx:idx+length] |
| 40 | + if sum(numbers[idx:idx+length]) == target: |
| 41 | + return contiguous_range |
| 42 | + return None |
| 43 | + |
| 44 | + |
| 45 | +def get_part1_answer(numbers): |
| 46 | + return find_invalid_number(numbers, 25) |
| 47 | + |
| 48 | + |
| 49 | +def get_part2_answer(numbers, invalid_num): |
| 50 | + contiguous_range = find_contiguous_sum(numbers, invalid_num) |
| 51 | + return min(contiguous_range) + max(contiguous_range) |
| 52 | + |
| 53 | + |
| 54 | +def run(): |
| 55 | + with open(util.get_input_file_path("day9.txt")) as f: |
| 56 | + numbers = [int(line) for line in f if len(line.strip()) > 0] |
| 57 | + invalid_num = get_part1_answer(numbers) |
| 58 | + print(f"The answer to part 1 is {invalid_num}") |
| 59 | + print(f"The answer to part 2 is {get_part2_answer(numbers, invalid_num)}") |
0 commit comments