Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
58-liner: It'd be better instead of 20 collisions, a limit distance where the fly dies. solution in Clear category for Escape by Stensen
from math import copysign
from itertools import starmap
def escape(jar, fly):
(W, H, d), (x0, y0, vx, vy) = jar, fly
if vy == 0:
return False
if vx == 0:
if (W-d)/2 <= x0 <= (W+d)/2:
return True
return False
# Line Equation Properties:
line = lambda x, y: (vy / vx, y - (vy / vx) * x)
# Copy sign units of the velocity:
sign = lambda vx, vy: tuple(starmap(copysign, [(1, vx), (1, vy)]))
# Line Equation: Point–slope Form
Y = lambda x: (vy / vx) * (x - x0) + y0
# Each loop create a Linear equaion from the slope (vx, vy) velocity
# And Passing from the Point(x0, y0)
# And Check Fly direction using the sign of (vx, vy)
# And Look for the intersection into the wall and so on 20 times.
for _ in range(20):
a, b = line(x0, y0)
# NORTH EAST LINES ARROW ⇗
if sign(vx, vy) == (1, 1):
if Y(W) <= H:
x0, y0 = W, Y(W)
vx *= -1
elif Y((H-b)/a) == H:
x0, y0 = (H-b)/a, H
vy *= -1
# NORTH WEST LINES ARROW ⇖
elif sign(vx, vy) == (-1, 1):
if Y(0) <= H:
x0, y0 = 0, Y(0)
vx *= -1
elif Y((H-b)/a) == H:
x0, y0 = (H-b)/a, H
vy *= -1
# SOUTH WEST LINES ARROW ⇙
elif sign(vx, vy) == (-1, -1):
if Y(0) >= 0:
x0, y0 = 0, Y(0)
vx *= -1
elif Y(-b/a) == 0:
x0, y0 = -b/a, 0
vy *= -1
# SOUTH EAST LINES ARROW ⇘
elif sign(vx, vy) == (1, -1):
if 0 <= Y(W) <= H:
x0, y0 = W, Y(W)
vx *= -1
elif Y(-b/a) == 0:
x0, y0 = -b/a, 0
vy *= -1
if (W-d)/2 < x0 < (W+d)/2 and y0 == H: return True
return False
Nov. 17, 2020
Comments: