Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Using Numpy solution in 3rd party category for Inside Block by BruceHoss
import numpy as np
PRECISION = 6
sgn = lambda x: 1 if x > 0 else 0 if x == 0 else -1
def asine(a, b):
x = np.arcsin(np.cross(a,b)/(a@a*b@b)**0.5)
return x if a@b >= 0 else np.pi * sgn(x) - x
def on_edge(a, b):
return a@b == -(a@a * b@b)**0.5
def is_inside(poly, pt):
vs = np.array(poly) - np.array(pt)
v_pairs = [(vs[n-1], vs[n]) for n in range(len(vs))]
return True if any(on_edge(*vp) for vp in v_pairs) \
else round(sum([asine(*vp) for vp in v_pairs]), PRECISION) != 0
if __name__ == '__main__':
assert is_inside(((1, 1), (1, 3), (3, 3), (3, 1)),
(2, 2)) == True, "First"
assert is_inside(((1, 1), (1, 3), (3, 3), (3, 1)),
(4, 2)) == False, "Second"
assert is_inside(((1, 1), (4, 1), (2, 3)),
(3, 2)) == True, "Third"
assert is_inside(((1, 1), (4, 1), (1, 3)),
(3, 3)) == False, "Fourth"
assert is_inside(((2, 1), (4, 1), (5, 3), (3, 4), (1, 3)),
(4, 3)) == True, "Fifth"
assert is_inside(((2, 1), (4, 1), (3, 2), (3, 4), (1, 3)),
(4, 3)) == False, "Sixth"
assert is_inside(((1, 1), (3, 2), (5, 1), (4, 3), (5, 5), (3, 4), (1, 5), (2, 3)),
(3, 3)) == True, "Seventh"
assert is_inside(((1, 1), (1, 5), (5, 5), (5, 4), (2, 4), (2, 2), (5, 2), (5, 1)),
(4, 3)) == False, "Eighth"
May 13, 2018
Comments: