Skip to content

Instantly share code, notes, and snippets.

@Shogun89
Created July 18, 2024 22:07
Show Gist options
  • Save Shogun89/b93bd47123eb9fc870ca9ee30824155d to your computer and use it in GitHub Desktop.
Save Shogun89/b93bd47123eb9fc870ca9ee30824155d to your computer and use it in GitHub Desktop.
Checks if points are in a triangle and draws it
import math
import matplotlib.pyplot as plt
def distance(x1, y1, x2, y2):
return math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
def is_triangle_non_degenerate(ax, ay, bx, by, cx, cy):
# Calculate the lengths of the sides
ab = distance(ax, ay, bx, by)
bc = distance(bx, by, cx, cy)
ca = distance(cx, cy, ax, ay)
# Check the triangle inequality theorem
return ab + bc > ca and ab + ca > bc and bc + ca > ab
def is_point_in_triangle(px, py, ax, ay, bx, by, cx, cy):
# Use the sign of areas method to check if the point is inside the triangle
def sign(x1, y1, x2, y2, x3, y3):
return (x1 - x3) * (y2 - y3) - (x2 - x3) * (y1 - y3)
b1 = sign(px, py, ax, ay, bx, by) < 0.0
b2 = sign(px, py, bx, by, cx, cy) < 0.0
b3 = sign(px, py, cx, cy, ax, ay) < 0.0
return b1 == b2 == b3
# Function to check both points p and q
def check_points_in_triangle(ax, ay, bx, by, cx, cy, px, py, qx, qy):
# Check if the triangle is non-degenerate
if not is_triangle_non_degenerate(ax, ay, bx, by, cx, cy):
return 0
# Check if point p is in the triangle
p_in_triangle = is_point_in_triangle(px, py, ax, ay, bx, by, cx, cy)
# Check if point q is in the triangle
q_in_triangle = is_point_in_triangle(qx, qy, ax, ay, bx, by, cx, cy)
if p_in_triangle and q_in_triangle:
return 3
elif p_in_triangle:
return 2
elif q_in_triangle:
return 1
else:
return 4
# Example usage
ax, ay = 0, 0
bx, by = 5, 0
cx, cy = 0, 5
px, py = 1, 1
qx, qy = 6, 6
result = check_points_in_triangle(ax, ay, bx, by, cx, cy, px, py, qx, qy)
# Plotting the triangle and points
plt.figure()
plt.plot([ax, bx], [ay, by], 'k-')
plt.plot([bx, cx], [by, cy], 'k-')
plt.plot([cx, ax], [cy, ay], 'k-')
plt.scatter([ax, bx, cx], [ay, by, cy], color='blue', label='Triangle vertices')
plt.scatter(px, py, color='green' if result in [2, 3] else 'red', label='Point p')
plt.scatter(qx, qy, color='green' if result in [1, 3] else 'red', label='Point q')
plt.legend()
plt.xlabel('x')
plt.ylabel('y')
plt.title('Triangle and Points p and q')
plt.grid(True)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment