summary refs log tree commit diff stats
path: root/day17.py
blob: 53881ea8b35dda40e666658572556fb47977b4e2 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#!/usr/bin/env python

# target area: 236 <= x <= 262, -78 <= y <= -58
# i was originally going to do a brute force solution
# since the problem implies that the displacement on the x axis is the Vx'th triangular number
# which gives a lower bound on the number of steps to calculate the displacement on the y axis
# but there's actually a really brilliant solution located at
# https://github.com/prendradjaja/advent-of-code-2021/blob/main/17--trick-shot/a.py
# which I am paraphrasing here

yvel = 77
print(sum(n for n in range(1, yvel+1)))


# part 2
xMin, xMax, yMin, yMax = 236, 262, -78, -58

def is_hit(vel):
    for pos in trajectory(vel):
        if xMin <= pos[0] <= xMax and yMin <= pos[1] <= yMax:
            return True
    return False

def trajectory(vel):
    pos = (0,0)
    while pos[0] <= xMax and pos[1] >= yMin:
        yield pos
        pos = (pos[0] + vel[0], pos[1] + vel[1])
        vel = (
            max(0, vel[0] - 1),
            vel[1] - 1
        )

result = 0
for xvel in range(0, xMax+1):
    for yvel in range(yMin, -yMin):
        if is_hit((xvel, yvel)):
            result += 1
print(result)