Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Clear, if not verbose. solution in Clear category for Escape by kkkkk
def correct_overshoot(width, height, x_1, y_1, x_2, y_2):
"""Return x, y value within jar's boundaries."""
# To use the formula 'y = mx + b', calculate the slope and bval.
slope = 0
if x_2 - x_1 != 0:
slope = (y_2 - y_1) / (x_2 - x_1)
b_val = y_1 - slope * x_1
# If we overshoot the jar's boundaries, calculate the adjusted
# x or y value.
if y_1 < 0 or y_1 > height:
y_1 = 0 if y_1 < 0 else height
x_1 = (y_1 - b_val) / slope if slope else x_1
if x_1 < 0 or x_1 > width:
x_1 = 0 if x_1 < 0 else width
y_1 = slope * x_1 + b_val
return x_1, y_1
def escape(jar, fly):
"""Return True if the fly can escape the jar from the given position."""
width, height, diameter = jar
x_0, y_0, v_x, v_y = fly
# Calculate the 'x' position of jar opening.
open_x = (width - diameter) // 2
closed_x = open_x + diameter
# Loop until the fly escapes or collapses.
escaped = False
pos_x = x_0
pos_y = y_0
for collision_cnt in range(20):
# Add the vector to the current position until a jar wall is hit.
last_x = pos_x
last_y = pos_y
while (pos_x >= 0 and pos_x <= width) and \
(pos_y >= 0 and pos_y <= height):
pos_x += v_x
pos_y += v_y
# If the new position exceeds the boundries of the jar, find the
# x or y intercept of the boundry.
pos_x, pos_y = correct_overshoot(width, height, pos_x, pos_y,
last_x, last_y)
# Made it through the jar opening?
if open_x < pos_x < closed_x and pos_y + v_y > height:
escaped = True
break
# Hit the top or bottom.
if pos_y == height or pos_y == 0:
v_y *= -1
# Hit a side.
if pos_x <= 0 or pos_x >= width:
v_x *= -1
return escaped
Nov. 24, 2019