2010年2月1日 星期一

Intersection of Date Ranges


function intersect($start1, $end1, $start2, $end2) {
return ($start1 >= $start2) ? ($start1 <= $end2) : ($start2 <= $end1);
}

$tests = array (
'First is on the far left ' => array(1, 2, 8, 9, False),
'First is on the far right' => array(8, 9, 1, 2, False),
'Identical ' => array(1, 9, 1, 9, True),
'Same start ' => array(1, 5, 1, 9, True),
'Same end ' => array(1, 9, 5, 9, True),
'First contains second ' => array(1, 9, 3, 7, True),
'Second contains first ' => array(3, 7, 1, 9, True),
'First end within second ' => array(1, 7, 3, 9, True),
'First start within second' => array(3, 9, 1, 7, True),
'First continues to second' => array(1, 5, 5, 9, True),
'Second continues to first' => array(5, 9, 1, 5, True),
);

foreach($tests as $test => $testData) {
list($start1, $end1, $start2, $end2, $expected) = $testData;
$intersects = intersect($start1, $end1, $start2, $end2);
echo
$test,
' Expected ', ($expected ? 'True ' : 'False'),
' Result ', ($intersects ? 'True ' : 'False'),
($expected === $intersects ? ' Passed' : ' Failed'),
PHP_EOL;
}

And the results ...

First is on the far left Expected False Result False Passed
First is on the far right Expected False Result False Passed
Identical Expected True Result True Passed
Same start Expected True Result True Passed
Same end Expected True Result True Passed
First contains second Expected True Result True Passed
Second contains first Expected True Result True Passed
First end within second Expected True Result True Passed
First start within second Expected True Result True Passed
First continues to second Expected True Result True Passed
Second continues to first Expected True Result True Passed


My only issue with this code is the ability to describe ranges that continue from each other.

The last 2 tests I would like to be able to return false on.

Range 1 is from 1 to 2
Range 2 is from 2 to 3

These could be considered as NON overlapping.

Currently both tests give the same result.

A word of warning, the ranges are inclusive. A range like 5,1 would mess things up a lot.



摘自:http://ryanfarley.com/blog/archive/2004/08/19/966.aspx

沒有留言:

wibiya widget