62 lines
1.3 KiB
Python
Raw Permalink Normal View History

2021-12-19 06:33:30 +01:00
#!/usr/bin/env python
import re
def get_velocity_x(target):
result = dict()
for x in range(max(target[0], target[1])+1):
result[x] = []
pos = 0
for i, speed in enumerate(reversed(range(x+1))):
if (target[0] <= pos <= target[1]):
result[x].append(i)
pos += speed
return result
def get_velocity_y(target):
result = dict()
min_y = min(target[2], target[3])
for y in range(min_y, abs(min_y)+1):
result[y] = []
pos = 0
i = 0
speed = y
while pos >= min_y:
i += 1
pos += speed
#print("%d %d %d %d" % (y, pos, speed, i))
if (target[2] <= pos <= target[3]):
result[y].append(i)
speed -= 1
return result
def get_max_heigth(velocity_x, velocity_y):
for y in reversed(velocity_y.keys()):
for x in velocity_x.keys():
sx = set(velocity_x[x])
sy = set(velocity_y[y])
if len(sx) == 0:
continue
if len(sy) == 0:
continue
s = sx.intersection(sy)
if len(s):
return int(y*(y+1)/2)
if velocity_x[x][-1] == x:
return int(y*(y+1)/2)
return None
with open("input01.txt","r") as f:
line = f.readline()
m = re.match(".*: x=(.*)\.\.(.*), y=(.*)\.\.(.*)", line.strip())
target = [int(m.group(1)), int(m.group(2)), int(m.group(3)), int(m.group(4))]
velocity_x = get_velocity_x(target)
velocity_y = get_velocity_y(target)
result = get_max_heigth(velocity_x, velocity_y)
print(result)