Integral Point Inside a Triangle
Given a triangle on a two-dimensional plane, output the integral point inside or on the boundaries of the triangle which has the minimum sum of distances from the
three vertices.
Input:
Coordinates (float number up to 3 decimal places) of three vertices are inputted as the x, y coordinate so that three vertices are:p1 = (x1,y1), p2= (x2,y2), p3=
(x3, y3).
Output:
- A list/array with integer coordinate [x, y] which the point has the minimum sum of distances from the three vertices.
- If there are no valid points, output [None, None]
- If there are multiple answers, output the one with the largest x-coordinate.
- If there are still multiple answers, output the one with the largest y-coordinate.
Sample input:
x1 = 0.0,y1=0.0,x2= 1.0,y2=0.0,x3= 1.0,y3= 1.0
Sample output:
[1, 0], point inside or on the boundary of the triangle, where the sum of distances from three vertices is minimum (equal to 2 in the example).
'''
首先判断给定的点是否在三角形内部:
A utility function to calculate area of triangle formed by (x1, y1), (x2, y2) and (x3, y3)
'''
# 定义area方程:计算三角形面积
def area(x1, y1, x2, y2, x3, y3):
return abs((x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) / 2.0)
'''
定义isInside方程,判断给定点P是否在三角形内部:
A function to check whether point P(x, y) lies inside the triangle formed by
A(x1, y1), B(x2, y2) and C(x3, y3)
'''
def isInside(x1, y1, x2, y2, x3, y3, x, y):
# Calculate area of triangle ABC
A = area (x1, y1, x2, y2, x3, y3)
# Calculate area of triangle PBC
A1 = area (x, y, x2, y2, x3, y3)
# Calculate area of triangle PAC
A2 = area (x1, y1, x, y, x3, y3)
# Calculate area of triangle PAB
A3 = area (x1, y1, x2, y2, x, y)
# Check if sum of A1, A2 and A3 is same as A
if(A == A1 + A2 + A3):
return 'Inside'
else:
return 'Outside'
#%%
# 测试:A(0, 0), B(20, 0), C(10, 30)
isInside(0, 0, 20, 0, 10, 30, 10, 15)