-1

can you help me with overlapping periods. I have array

["1-9","11-15","14-20","8-11"]

Each element in array its period. Min - 1 period, max - 10 periods in array. I need to detect if they are overlapping.

I find this cases from another question

image

Narendrasingh Sisodia
  • 19,948
  • 5
  • 40
  • 50
Vladislav
  • 93
  • 1
  • 3

2 Answers2

0

This is a simple snippet that way of its checking is based on comparing highest end of first range to lowest end of second range (if we only consider that ranges are valid). And at the first place, sorting ranges is playing an important role:

$ranges = ["1-9","11-15","14-20","8-11"];
$results = [];
sort($ranges, SORT_NUMERIC);
foreach ($ranges as $first) {
    $firstNums = explode("-", $first);
    foreach ($ranges as $second) {
        if ($first == $second) continue;
        $secondNums = explode("-", $second);
        if ($firstNums[1] >= $secondNums[0] && $first != end($ranges)) {
            $results[$first] = $second;
        }
    }
}
print_r($results);

Results (which contain both dates that overlap):

Array
(
    [1-9] => 8-11
    [8-11] => 11-15
    [11-15] => 14-20
)
revo
  • 43,830
  • 14
  • 67
  • 109
0

This should cover all the scenarios :

<?php

public function findOverlappingPeriods(array $periods): array
{
    $overlappingItems = [];

    foreach ($periods as $keyA => $periodA) {
        foreach ($periods as $keyB => $periodB) {
            if ($keyA === $keyB) {
                continue;
            }

            if ($periodB['start'] > $periodA['start'] && $periodB['start'] < $periodA['end']) {
                $overlappingItems[] = $keyA;
                $overlappingItems[] = $keyB;
            }
        }
    }

    return $overlappingItems;
}
axelvnk
  • 414
  • 5
  • 14