开发者

What is a tidy algorithm to find overlapping intervals?

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


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)


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜