找到重叠间隔的整洁算法是什么?
我确信以前肯定有人问过这个问题,但我没有找到它:我只是找到相关但更难的问题。
我有四个点,代表两条线,如下所示:
A C B D
|------*---|-----+----|-*---+---|----------|
0 10 20 30 40
因此在示例中,AB = {7, 21}
和 CD = {16,26}
。 (这些线彼此之间可以有任何关系,也可以有任何大小。)我想知道它们是否重叠,如果重叠的话,重叠多少。 (在这个例子中,答案是 5。)我当前的解决方案涉及一堆复杂的 if/then 步骤,我忍不住认为有一个很好的算术解决方案。有没有?
(PS:真的,我正在做边界框相交,但如果我能在一个维度上得到它,显然另一个维度将是相同的。)
I'm sure this must have been asked before, but I'm not finding it: I'm only finding related, but harder questions.
I've got four points, representing two lines like this:
A C B D
|------*---|-----+----|-*---+---|----------|
0 10 20 30 40
So in the example, AB = {7, 21}
and CD = {16,26}
. (The lines could be in any relation to each other, and any size.) I want to find out whether or not they overlap, and by how much if so. (In the example, the answer would be 5.) My current solution involves a bunch of complicated if/then steps, and I can't help but think there's a nice arithmetical solution. Is there?
(P.S. Really, I'm doing bounding-box intersection, but if I can get it in one dimension, the other will be the same, obviously.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
试试这个:
如果您可以假设
a <= b
和c <= d
:您还可以计算
相交
,如下所示:Try this:
If you can assume
a <= b
andc <= d
:You can also calculate
intersects
as follows:线段是两条相对射线(相反方向的两条半无限直线)的交点。有两条线段相交——结果是所有 4 条射线的交点。因此,您可以将代码分解为三个连续的光线相交:左侧光线的左侧与右侧光线的右侧相交。
(这是陈述现已接受的答案的另一种方式。)
A line segment is the intersection of two opposing rays (two half-infinite lines in opposite directions). You have two line segments to intersect -- the result is the intersection of all 4 rays. So you can factor your code as three successive ray-intersections: the leftward of the left-facing rays intersected with the rightward of the right-facing rays.
(This is another way of stating the now-accepted answer.)