Reputation: 253
I have a GridView, Which has three columns Name, Start Date and End Date. Time Ranges are in sorted order. Means GridView is sorted by Start Date by default. User wants to insert a new Row with Name, Start Date and End Date. If time Span between new Start Date and new End Date intersects with any other(could be more than one Row) time spans of other rows. Those row will be deleted and this new Record will be inserted in GridView. If there is no intersection with any of the time span then simply it will be added to the GridView.
If have written the following code to find out intersection between two Dates (datatype is DateTime).
public class DateTimeRange
{
public DateTime Start { get; set; }
public DateTime End { get; set; }
public bool Intersects(DateTimeRange test)
{
if (this.Start > this.End || test.Start > test.End)
return false;
//throw new InvalidDateRangeException();
if (this.Start == this.End || test.Start == test.End)
return false; // No actual date range
if (this.Start == test.Start || this.End == test.End)
return true; // If any set is the same time, then by default there must be some overlap.
if (this.Start < test.Start)
{
if (this.End > test.Start && this.End < test.End)
return true; // Condition 1
if (this.End > test.End)
return true; // Condition 3
}
else
{
if (test.End > this.Start && test.End < this.End)
return true; // Condition 2
if (test.End > this.End)
return true; // Condition 4
}
return false;
}
}
So I am planning to iterate the GridView row wise(one by one), store the index of Rows which are intersecting with new recode. and after iteration I will delete rows of these indexes and insert new Recode. So my Doubt is there any better way to do this in less complexity or in easier way.
Precondition: All time ranges are mutually exclusive initially, means there is no intersection among rows.
Upvotes: 1
Views: 587
Reputation: 11597
Two sets a and b do not intersect in these cases:
---|<--A-->|----------------
-------------|<--B-->|------
a.End < b.Start
--------------|<--A-->|-----
---|<--B-->|----------------
a.Start > b.End
So if you combine the two cases you get:
a.End < b.Start || a.Start > b.End
Now you can negate it:
!(a.End < b.Start || a.Start > b.End)
To optimize, using De Morgan you obtain:
a.End >= b.Start && a.Start <= b.End
This last condition tells you that they not
do don't intersect
(double negation).
So they intersect.
Border conditions are excluded. Replace <
/>
with <=
/>=
and vice versa to have it the other way around.
Upvotes: 3