2017-02-13 254 views
3

我有一个时间戳和持续时间数组以及占用的时间戳数组。 我现在需要检查这些时间戳是否发生碰撞。如果时间戳范围在时间戳范围内

基本上$启动[]不能内任何$占用[]时间戳

$start[0] = 1486987200; // 12:00 
$duration[0] = 3600; 

$start[1] = 1487008800; // 18:00 
$duration[1] = 7200; 

$occupied[0] = 1486989000; // 12:30 
$ocDuration[0] = 3600; 

$occupied[1] = 1487019600; // 21:00 
$ocDuration[1] = 7200; 

从上述$start[0]是不可能的,因为$occupied[0]是它的取值范围为1小时(3600秒)的范围内,但$start[1]是可能的,因为它从18:00开始,并在2小时后结束。

enter image description here

另一种情况可能是,当$occupied[0]二者重叠$start[]

enter image description here

所以现在的问题是,我该怎么办这样的检查?

+0

喜爱的描述和示范 – Ima

+0

对于这种事情的[间隔树](https://en.wikipedia.org/wiki/Interval_tree)是一种优良的数据结构。我不知道是否有一个PHP的实现;但是我已经在Python库上成功构建了类似的东西,比如[this](https://pypi.python.org/pypi/intervaltree)。 – deceze

+0

感谢您的回复。我会研究间隔树。似乎这可能是未来的好事 – JPJens

回答

0
function checkTimeSlot($occupied, $occDuration, $checkStart, $checkDuration) 
{ 
    $isValid = true; 
    foreach($occupied as $key => $occStartTime) 
    { 
     $occEndTime = $occStartTime + $occDuration; 
     if($checkStart > $occStartTime || $checkStart < $occEnd || $occEndTime > $occStartTime || $occEndTime < $occEndTime) 
     { 
      $isValid = false; 
     } 
    } 

    return $isValid; 
} 


$isValid = []; 
foreach ($start as $key => $checkStart) 
{ 
    $isValid[$key] = checkTimeSlot($checkStart, $duration[$key]); 
} 
1

如果您将$ start和$ duration用作非数组变量,则可以使用下面的这个。否则,只需编写一个双重for循环。

$start[0] = 1486987200; // 12:00 
$duration[0] = 3600; 

$start[1] = 1487008800; // 18:00 
$duration[1] = 7200; 

$occupied[0] = 1486989000; // 12:30 
$ocDuration[0] = 3600; 

$occupied[1] = 1487019600; // 21:00 
$ocDuration[1] = 7200; 

$occupied[2] = 1486989000; // 12:30 
$ocDuration[2] = 23400; 

function checkOccupancy($start, $duration, $occupied, $ocDuration){ 
    $ocLength = count($occupied); 
    for($i = 0; $i <= $ocLength; $i++){ 
     $ocEnd = $occupied[$i] + $ocDuration[$i]; 
     $end = $start + $duration; 
     if(($start > $occupied[$i] && $start < $ocEnd) || ($end > $occupied[$i] && $end < $ocEnd)){ 
      return "Not Possible"; 
     } 
    } 
    return "Possible"; 
} 

echo checkOccupancy($start[0], $duration[0], $occupied, $ocDuration); 
echo checkOccupancy($start[1], $duration[1], $occupied, $ocDuration);