Files
advent-of-code-2021/day-17/day-17.py
Pascal Lais a81a510d6b
All checks were successful
continuous-integration/drone/push Build is passing
Update day 17 solution
2021-12-17 16:58:18 +01:00

56 lines
2.1 KiB
Python

#!/usr/bin/env python3
from pathlib import Path
def part_1(input):
"""The max height is reached by using the maximum start y velocity that doesn't overshoot the
landing area. The x velocity doesn't mater here, because x position won't change after x
velocity reaches 0. So there will always be an vx that drops straight between the x boundaries.
Because the y velocity decreases linear we will reach our starting height after the velocity
changed exactly to the negative value of our starting velocity. At this point we have to make
sure not to overhoot the landing area, so the next velocity needs to be the same value as the
lowest coordinate of the landing area to be able to start with the highest possible starting
velocity. This leaves us with a starting velocity of abs(y_min + 1) to reach the maximum
possible height. For positive landing coordinates y_max has to be used.
"""
result = 0
_, y = input[0].rstrip().replace('target area: ', '').replace(
'x=', '').replace('y=', '').split(', ')
y_min, _ = [int(c) for c in y.split('..')]
vy0 = abs(y_min + 1)
result = vy0 * (vy0 + 1) // 2
print("Part 1 result:", result)
def part_2(input):
result = 0
x, y = input[0].rstrip().replace('target area: ', '').replace(
'x=', '').replace('y=', '').split(', ')
x_min, x_max = [int(c) for c in x.split('..')]
y_min, y_max = [int(c) for c in y.split('..')]
for vx_0 in range(x_max):
for vy_0 in range(y_min, -y_min):
vx = vx_0
vy = vy_0
x_pos = 0
y_pos = 0
while x_pos < x_max and y_pos > y_min:
x_pos += vx
y_pos += vy
if vx != 0:
vx -= 1
vy -= 1
if x_min <= x_pos <= x_max and \
y_min <= y_pos <= y_max:
result += 1
break
print("Part 2 result:", result)
input = list()
p = Path(__file__).with_name('input.txt')
with open(p) as f:
input = f.readlines()
part_1(input)
part_2(input)