Поиск пересений отрезков (времени) в массивах - Разбор алгоритмической задачи с собеседований
Primary tabs
Forums:
(в процессе решения)
<?php
$a = [[1, 5], [7, 10], [12, 24]];
$b = [[4, 6], [12, 13], [30, 35]];
print_r(getIntersectIntervals($a, $b));
function getIntersectIntervals(array $a, array $b): array {
$result = [];
$bCount = count($b);
$start = 0;
foreach($a as $interval) { // будем перебирать весь массив, л
for ($i = $start; $i < $bCount; $i++) {
[$intersect, $has_second_something_in_future] = getIntersect($interval[0], $interval[1], $b[$i][0], $b[$i][1]);
if (!empty($intersect)) {
$result[] = $intersect;
}
// if (!$has_second_something_in_future) {
// $start++;
// }
}
}
return $result;
}
function getIntersect(int $a, int $b, int $c, int $d): array {
$instersect = [];
$left = $a > $c ? $a : $c;
$has_second_something_in_future = $d > $b;
$right = $has_second_something_in_future ? $b : $d;
$instersect = $left <= $right ? [$left, $right] : [];
return [$instersect, $has_second_something_in_future];
}
- Log in to post comments
- 30 reads