Advertisement
Guest User

Day 17

a guest
Dec 17th, 2021
214
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.77 KB | None | 0 0
  1. def can_visit_target(x_velocity, y_velocity, lower_x, upper_x, lower_y, upper_y):
  2. x = y = 0
  3.  
  4. while x <= upper_x and y >= lower_y:
  5. if lower_x <= x <= upper_x and lower_y <= y <= upper_y:
  6. return True
  7.  
  8. x += x_velocity
  9. y += y_velocity
  10. y_velocity -= 1
  11. x_velocity = max(0, x_velocity - 1)
  12.  
  13. return False
  14.  
  15.  
  16. def get_min_x_velocity(lower_x, upper_x):
  17. for i in range(upper_x+1):
  18. if lower_x <= i * (i + 1) // 2 <= upper_x:
  19. return i
  20.  
  21. return -1
  22.  
  23.  
  24. def solve_part_1(lower_x, upper_x, lower_y, upper_y):
  25. min_x_velocity = get_min_x_velocity(lower_x, upper_x)
  26. max_y_velocity = 0
  27.  
  28. for y_velocity in range(lower_y, abs(lower_y)):
  29. if can_visit_target(min_x_velocity, y_velocity, lower_x, upper_x, lower_y, upper_y):
  30. max_y_velocity = max(max_y_velocity, y_velocity)
  31.  
  32. return max_y_velocity * (max_y_velocity + 1) // 2
  33.  
  34.  
  35. def solve_part_2(lower_x, upper_x, lower_y, upper_y):
  36. min_x_velocity = get_min_x_velocity(lower_x, upper_x)
  37. count = 0
  38.  
  39. for x in range(min_x_velocity, upper_x + 1):
  40. for y in range(lower_y, abs(lower_y)):
  41. count += can_visit_target(x, y, lower_x, upper_x, lower_y, upper_y)
  42.  
  43. return count
  44.  
  45.  
  46. if __name__ == '__main__':
  47. with open('input_01.txt') as f:
  48. coords = f.readline().strip().split(': ')[1]
  49. x_coords, y_coords = coords.split(', ')
  50.  
  51. lower_x, upper_x = x_coords.split('..')
  52. lower_x, upper_x = int(lower_x[2:]), int(upper_x)
  53.  
  54. lower_y, upper_y = y_coords.split('..')
  55. lower_y, upper_y = int(lower_y[2:]), int(upper_y)
  56.  
  57. print(solve_part_1(lower_x, upper_x, lower_y, upper_y))
  58. print(solve_part_2(lower_x, upper_x, lower_y, upper_y))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement