找到重叠间隔的整洁算法是什么?

发布于 2024-10-16 03:25:02 字数 460 浏览 3 评论 0原文

我确信以前肯定有人问过这个问题,但我没有找到它:我只是找到相关但更难的问题。

我有四个点,代表两条线,如下所示:

       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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

暖伴 2024-10-23 03:25:02

试试这个:

intersects = (max(a,b) > min(c,d)) && (min(a,b) < max(c,d))
overlap = min(max(a,b), max(c,d)) - max(min(c,d), min(a,b))

如果您可以假设 a <= bc <= d

intersects = (b > c) && (a < d)
overlap = min(b, d) - max(c, a)

您还可以计算 相交,如下所示:

intersects = (overlap > 0)

Try this:

intersects = (max(a,b) > min(c,d)) && (min(a,b) < max(c,d))
overlap = min(max(a,b), max(c,d)) - max(min(c,d), min(a,b))

If you can assume a <= b and c <= d:

intersects = (b > c) && (a < d)
overlap = min(b, d) - max(c, a)

You can also calculate intersects as follows:

intersects = (overlap > 0)
意中人 2024-10-23 03:25:02

线段是两条相对射线(相反方向的两条半无限直线)的交点。有两条线段相交——结果是所有 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.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文