中级农民
- 积分
- 108
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2016-11-2
- 最后登录
- 1970-1-1
|
Tag: geometry
input lines: [(x,y),(x,y),(x,y),(x,y)] 很多个点的x,y
核心:如果p3p4 要和p1p2相交,
1. 当p2p3在p1p2 顺时针或逆时针方向, p2p4在p1p2 和前者相反的方向,
2. p1p3在p3p4 顺时针或逆时针方向,p2p3在p3p4 和前者相反的方向。
或者另一条边的一个点在线上
废话不多说 上代码
- class Intersection:
- def find_intersections(self, lines):
- n = len(lines)
- res = 0
- for i in range(n):
- for j in range(i+1, n):
- if self.intersect(lines[i][0], lines[i][1], lines[j][0], lines[j][1]):
- res += 1
- return res
-
- # if p1p2 intersect with p3p4
- def intersect(self, p1, p2, p3, p4):
- o1,o2,o3,o4 = self.orientation(p1, p2, p3), self.orientation(p1, p2, p4), self.orientation(p3, p4, p1), self.orientation(p3, p4, p2)
- # p3 and p4 is different orientation to p1 and p3 and p4 is different orientation to p2
- # p1 and p2 is different orientation to p3 and p1 and p1 is different orientation to p4
- if o1 != o2 and o3!=o4:
- return True
- # if p3 is on p1p2 and p1p2 and p2p3 has same slope
- if o1 == 0 and self.on(p1,p2,p3):
- return True
- # if p4 is on p1p2 and p1p2 and p2p4 has same slope
- if o2 == 0 and self.on(p1,p2,p4):
- return True
- if o3 == 0 and self.on(p3,p4,p1):
- return True
- if o4 == 0 and self.on(p3,p4,p2):
- return True
- return False
- # p3p2 is counter clock wise or clock wise of p1p2
- def orientation(self, p1, p2, p3):
- #slope1 = p2[1]-p1[1] / p2[0] - p1[0]
- #sloep2 = p3[1]-p2[1] / p3[0] - p3[0]
- # slope1 - slope2 = (p2[1]-p1[1]) * (p3[0] - p3[0]) - (p3[1]-p2[1]) * (p2[0] - p1[0])
- diff = (p2[1]-p1[1]) * (p3[0] - p3[0]) - (p3[1]-p2[1]) * (p2[0] - p1[0])
- # 2 slope equal in the same line
- if diff == 0:
- return 0
- # slope1 > slope2 -> p2p3 is counter clock wise of p1p2
- if diff > 0:
- return 1 #
- # slope1 > slope2 -> p2p3 is clock wise of p1p2
- return 2
-
- # p3 is on p1p2
- def on(self, p1,p2,p3):
- maxx,maxy,minx,miny = max(p1[0],p2[0]), max(p1[1],p2[1]), min(p1[0],p2[0]), min(p1[1],p2[1])
- return minx <= p3[0] <= maxx and miny <= p3[1] <= maxy
复制代码
求个大米
|
|