/ Python / 2021 / 17.py
17.py
 1  from lib import *
 2  
 3  input = read_input(2021, 17)
 4  
 5  
 6  match = re.match(r"^target area: x=(-?\d+)..(-?\d+), y=(-?\d+)..(-?\d+)$", input)
 7  y1 = int(match.group(3))
 8  print(y1 * (y1 + 1) // 2)
 9  
10  
11  x1, x2, y1, y2 = map(int, match.groups())
12  ok = {}
13  maxt = 0
14  for vy in range(y1, -y1 + 1):
15      ovy = vy
16      t = 0
17      y = 0
18      while y >= y1:
19          if y1 <= y <= y2:
20              ok.setdefault(t, set()).add(ovy)
21              maxt = max(t, maxt)
22          y += vy
23          vy -= 1
24          t += 1
25  
26  out = 0
27  for vx in range(x2 + 1):
28      if (vx + 1) ** 2 - (vx + 1) * (vx + 2) // 2 < x1:
29          continue
30  
31      t = 0
32      x = 0
33      found = set()
34      while x <= x2 and t <= maxt:
35          if x1 <= x <= x2:
36              found.update(ok.get(t, []))
37          x += vx
38          vx = max(vx - 1, 0)
39          t += 1
40      out += len(found)
41  
42  print(out)