检测重叠时段的算法 [英] Algorithm to detect overlapping periods
问题描述
我必须检测两个时间段是否重叠.
每个时期都有一个开始日期和一个结束日期.
我需要检测我的第一个时间段 (A) 是否与另一个时间段 (B/C) 重叠.
就我而言,如果 B 的开头等于 A 的结尾,则它们不重叠(反之亦然)
我发现了以下情况:
I've to detect if two time periods are overlapping.
Every period has a start date and an end date.
I need to detect if my first time period (A) is overlapping with another one(B/C).
In my case, if the start of B is equal to the end of A, they are not overlapping(the inverse too)
I found the following cases:
所以实际上我是这样做的:
So actually I'm doing this like this:
tStartA < tStartB && tStartB < tEndA //For case 1
OR
tStartA < tEndB && tEndB <= tEndA //For case 2
OR
tStartB < tStartA && tEndB > tEndA //For case 3
(案例4在案例1或案例2中的帐户中)
(The case 4 is taken in the account either in case 1 or in case 2)
它有效,但似乎效率不高.
所以,首先在 c# 中有一个现有的类可以对此(时间段)进行建模,类似于时间跨度,但具有固定的开始日期.
So, first is there an existing class in c# that can modelize this(a time period), something like a timespan, but with a fixed start date.
其次:是否已经有一个 c# 代码(比如在 DateTime
类中)可以处理这个问题?
Secondly: Is there already a c# code(like in the DateTime
class) which can handle this?
第三:如果不是,你会用什么方法来最快地进行这种比较?
Third: if no, what would be your approach to make this comparison the most fast?
推荐答案
简单检查两个时间段是否重叠:
Simple check to see if two time periods overlap:
bool overlap = a.start < b.end && b.start < a.end;
或在您的代码中:
bool overlap = tStartA < tEndB && tStartB < tEndA;
(如果您改变主意想说两个只是相互接触的句点重叠,请使用 <=
而不是 <
.)
(Use <=
instead of <
if you change your mind about wanting to say that two periods that just touch each other overlap.)
这篇关于检测重叠时段的算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!