mirror of
https://github.com/Noettore/AdventOfCode.git
synced 2025-10-15 03:36:39 +02:00
AoC 2020: day9, refactored part2 with O(n) solution
Signed-off-by: Ettore Dreucci <ettore.dreucci@gmail.com>
This commit is contained in:
@@ -48,16 +48,17 @@ def part1(entries: list, preamble_length: int) -> int:
|
||||
|
||||
def part2(entries: list, invalid_number: int) -> int:
|
||||
"""part2 solver"""
|
||||
for index, _ in enumerate(entries):
|
||||
test_set = [entries[index]]
|
||||
test_set_len = 1
|
||||
while test_set_len < len(entries) - index:
|
||||
test_set.append(entries[index+test_set_len])
|
||||
test_set_len += 1
|
||||
|
||||
if sum(test_set) == invalid_number:
|
||||
return min(test_set) + max(test_set)
|
||||
return None
|
||||
left, right = 0, 1
|
||||
interval_sum = entries[left] + entries[right]
|
||||
while True:
|
||||
if interval_sum < invalid_number:
|
||||
right += 1
|
||||
interval_sum += entries[right]
|
||||
elif interval_sum > invalid_number:
|
||||
interval_sum -= entries[left]
|
||||
left += 1
|
||||
else:
|
||||
return min(entries[left:right+1]) + max(entries[left:right+1])
|
||||
|
||||
def test_input_day_9():
|
||||
"""pytest testing function"""
|
||||
|
@@ -16,8 +16,8 @@
|
||||
| [Day 4](https://adventofcode.com/2020/day/4) | [21.806ms](./2020-python/solutions/day_4.py) |
|
||||
| [Day 5](https://adventofcode.com/2020/day/5) | [5.993ms](./2020-python/solutions/day_5.py) |
|
||||
| [Day 6](https://adventofcode.com/2020/day/6) | [2.587ms](./2020-python/solutions/day_6.py) |
|
||||
| [Day 7](https://adventofcode.com/2020/day/7) | [1.689ms](./2020/python/solutions/day_7.py) |
|
||||
| [Day 8](https://adventofcode.com/2020/day/8) | [6.313ms](./2020/python/solutions/day_8.py) |
|
||||
| [Day 9](https://adventofcode.com/2020/day/9) | [552.396ms](./2020/python/solutions/day_9.py) |
|
||||
| [Day 7](https://adventofcode.com/2020/day/7) | [1.689ms](./2020-python/solutions/day_7.py) |
|
||||
| [Day 8](https://adventofcode.com/2020/day/8) | [6.313ms](./2020-python/solutions/day_8.py) |
|
||||
| [Day 9](https://adventofcode.com/2020/day/9) | [7.2207ms](./2020-python/solutions/day_9.py) |
|
||||
|
||||
|
||||
|
Reference in New Issue
Block a user