算法测试系列: Integral Point Inside a Triangle

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).

Check the Answer 1

Check the Answer 2


'''
首先判断给定的点是否在三角形内部:
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)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值