How to tell if two intervals intersect(区间判断)


Suppose we have two half-open intervals

[A, B) [X, Y)

and we want to know whether they intersect. In any particular case, it's obvious. For example

[1, 2) [3, 4)	disjoint
[1, 5) [3, 4)	intersect

But can we write a rule that covers the general case? Let's see...the first interval could contain the second, or it could overlap on the left, or on the right, or...this is getting complicated...

Here's how to do it.

There are 24 permutations of the 4 endpoints, but only 6 satisfy the conditions A < B and X < Y. These are

A B X Y
A X B Y  intersect
A X Y B  intersect
X A B Y  intersect
X A Y B  intersect
X Y A B

The four in the middle intersect, and the two on the ends do not.

The first is identified by B <= X, a condition that holds for it and no other, and the last is identified by Y <= A, a condition that holds for it and no other. Both comparison have an open bound on the left and a closed bound on the right, so a <= comparison is appropriate.

We can identify the four intersecting cases with the condition

NOT (B <= X OR Y <= A)

or, distributing the NOT

X < B AND A < Y
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值