From 4e1c71b221c24849e977284979085ce5f103fbff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mika=C3=ABl=20Capelle?= Date: Wed, 6 Dec 2023 07:13:53 +0100 Subject: [PATCH] 2023 day 6. --- 2023/day6.py | 49 ++++++++++++++++++++++++++++++++++++++++---- 2023/inputs/day6.txt | 2 ++ 2023/tests/day6.txt | 2 ++ 3 files changed, 49 insertions(+), 4 deletions(-) diff --git a/2023/day6.py b/2023/day6.py index 992bf35..0c4a864 100644 --- a/2023/day6.py +++ b/2023/day6.py @@ -1,13 +1,54 @@ +import operator import sys -from collections import defaultdict -from dataclasses import dataclass +from functools import reduce lines = sys.stdin.read().splitlines() + +def extreme_times_to_beat(time: int, distance: int) -> tuple[int, int]: + import math + + # formula + # - distance = (T - t) * t + # - (T - t) * t >= D + # - T * t - t^2 - D >= 0 + + a = -1 + b = time + c = -distance + + d = b * b - 4 * a * c + + t1 = math.ceil(-(b - math.sqrt(d)) / (2 * a)) + t2 = math.floor(-(b + math.sqrt(d)) / (2 * a)) + + if (time - t1) * t1 == distance: + t1 += 1 + + if (time - t2) * t2 == distance: + t2 -= 1 + + return t1, t2 + + # part 1 -answer_1 = ... +times = list(map(int, lines[0].split()[1:])) +distances = list(map(int, lines[1].split()[1:])) +answer_1 = reduce( + operator.mul, + ( + t2 - t1 + 1 + for t1, t2 in ( + extreme_times_to_beat(time, distance) + for time, distance in zip(times, distances) + ) + ), +) print(f"answer 1 is {answer_1}") # part 2 -answer_2 = ... +time = int(lines[0].split(":")[1].strip().replace(" ", "")) +distance = int(lines[1].split(":")[1].strip().replace(" ", "")) +t1, t2 = extreme_times_to_beat(time, distance) +answer_2 = t2 - t1 + 1 print(f"answer 2 is {answer_2}") diff --git a/2023/inputs/day6.txt b/2023/inputs/day6.txt index e69de29..01c2b63 100644 --- a/2023/inputs/day6.txt +++ b/2023/inputs/day6.txt @@ -0,0 +1,2 @@ +Time: 59 79 65 75 +Distance: 597 1234 1032 1328 diff --git a/2023/tests/day6.txt b/2023/tests/day6.txt index e69de29..28f5ae9 100644 --- a/2023/tests/day6.txt +++ b/2023/tests/day6.txt @@ -0,0 +1,2 @@ +Time: 7 15 30 +Distance: 9 40 200