开发者

Determine if ranges overlap

开发者 https://www.devze.com 2023-02-05 00:04 出处:网络
Given two events with integer start and end t开发者_运维问答imes, E1 = (s1, e1), E2 = (s2, e2), implement a quick boolean check to see if the events overlap.

Given two events with integer start and end t开发者_运维问答imes, E1 = (s1, e1), E2 = (s2, e2), implement a quick boolean check to see if the events overlap.

I have the solution, but I'm curious to see what others come up with.

EDIT: OK, here's my solution:

e1 > s2 || (s1 > s2 && e2 < s1)


bool overlap = (s1 <= e2) && (s2 <= e1)


Fred's answer is both concise and correct.

I prefer:

bool overlap = !(e1 < s2 || e2 < s1);

I think this is clearer, but it is a very small difference.

Converted to english:

They overlap if neither ends before the other starts.


This is similar to the overlapping rectangles problem. There are two good ways to write that test. They correspond to the statements:

Two rectangles overlap if the left edge of both is to the left of the right edge of the other, and the top edge of both is above the bottom edge of the other.


Two rectangles overlap if neither is to the left or above the other.


They overlap if:

  • e1 between (inclusive of both endpoints) s2 and e2 OR
  • e2 between (inclusive of both endpoints) s1 and e1


This will also work:

max(s1, s2) < min(e1, e2)


I would do it like this:

return s1 < s2 ? s2 <= e1 : s1 <= e2;


(S2-S1)<(e1-s1) || (S1-S2)<(e2-s2)


/* return true if intervals overlap */
bool overlap(unsigned int s1, unsigned int e1, unsigned int s2, unsigned int e2) {
    return (s1 >= s2 && s1 <= e2) ||
            (e1 >= s2 && e1 <= e2) ||
            (s2 >= s1 && s2 <= e1) ||
            (e2 >= s1 && e2 <= e1);
}


(s2 < s1 && s1 < e2) || (s1 < s2 && s2 < e1)

or, equivalently:

(s2 < s1 && s1 < e2) || (s2 < e1 && e1 < e2)


You can check In which cases It will not overlap

Condition for no overlap is :: (s2 > e1 ) || ( e2 > s1) so overlap is !((s2 > e1 ) || ( e2 > s1))

0

精彩评论

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