我有一堆坐标点,即((0,1),( - 1,-2))等。 如何验证两个坐标点是否接触?
如下所示(差),坐标(3,1)和(1,2)触摸/交叉?
|y
|
|- 2| (1,2)
| |
|-----------| (3,1)
| | |
----|---|---|---+---|---|---|----
x -3 -2 -1 | 1 2 3
|
|
| -2
|
| -3
|
他们在点(1,1)处交叉/触碰。我不需要交叉点,我只需要知道它们是否交叉。
答案 0 :(得分:1)
我将计算两个点从(x,y)到(x,0)和(0,y)的路径的坐标,并简单地检查这两个点的坐标之间是否存在交点。我相信会产生你想要的结果。
# All coordinates on paths from (x,y) to (x,0) and from (x,y) to (0,y)
def path(point)
x, y = point
coords_x = (x >= 0 ? [*0..x] : [*x..0]).map { |c| [c, y] }
coords_y = (y >= 0 ? [*0..y] : [*y..0]).map { |c| [x, c] }
coords_x | coords_y
end
# p1 and p2 share a coordinate on their paths to (x,0) / (0,y) from (x,y)
def cross(p1, p2)
( path(p1) & path(p2) ).any?
end
p1 = [3,1]
p2 = [1,2]
cross(p1,p2) # => true
p1 = [0,0]
p2 = [0,-3]
cross(p1,p2) # => true
p1 = [-5,-5]
p2 = [-5,5]
cross(p1,p2) # => true
p1 = [-3,-3]
p2 = [3,3]
cross(p1,p2) # => false