Copybara bot | be50d49 | 2023-11-30 00:16:42 +0100 | [diff] [blame] | 1 | <?php |
Adrià Vilanova Martínez | 5af8651 | 2023-12-02 20:44:16 +0100 | [diff] [blame] | 2 | /* |
| 3 | * hores |
| 4 | * Copyright (c) 2023 Adrià Vilanova Martínez |
| 5 | * |
| 6 | * This program is free software: you can redistribute it and/or modify |
| 7 | * it under the terms of the GNU Affero General Public License as |
| 8 | * published by the Free Software Foundation, either version 3 of the |
| 9 | * License, or (at your option) any later version. |
| 10 | * |
| 11 | * This program is distributed in the hope that it will be useful, |
| 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 14 | * GNU Affero General Public License for more details. |
| 15 | * |
| 16 | * You should have received a copy of the GNU Affero General Public |
| 17 | * License along with this program. |
| 18 | * If not, see http://www.gnu.org/licenses/. |
| 19 | */ |
| 20 | |
Copybara bot | be50d49 | 2023-11-30 00:16:42 +0100 | [diff] [blame] | 21 | class intervals { |
| 22 | public static function wellFormed($i) { |
| 23 | return (isset($i[0]) && isset($i[1]) && $i[0] <= $i[1]); |
| 24 | } |
| 25 | |
| 26 | public static function measure($i) { |
| 27 | return ($i[1] - $i[0]); |
| 28 | } |
| 29 | |
| 30 | // Does A overlap B? (with "$open = true" meaning [0, 100] does not overlap [100, 200]) |
| 31 | public static function overlaps($a, $b, $open = true) { |
| 32 | return ($open ? ($a[0] < $b[1] && $a[1] > $b[0]) : ($a[0] <= $b[1] && $a[1] >= $b[0])); |
| 33 | } |
| 34 | |
| 35 | // Is A inside of B? |
| 36 | public static function isSubset($a, $b) { |
| 37 | return ($a[0] >= $b[0] && $a[1] <= $b[1]); |
| 38 | } |
| 39 | |
| 40 | // Intersect A and B and return the corresponding interval |
| 41 | public static function intersect($a, $b) { |
| 42 | $int = [max($a[0], $b[0]), min($a[1], $b[1])]; |
| 43 | |
| 44 | return (self::wellFormed($int) ? $int : false); |
| 45 | } |
| 46 | |
| 47 | // Return measure of the intersection |
| 48 | public static function measureIntersection($a, $b) { |
Adrià Vilanova Martínez | 330847d | 2023-12-20 23:51:34 +0100 | [diff] [blame] | 49 | $intersection = self::intersect($a, $b); |
| 50 | if ($intersection === false) return 0; |
| 51 | return self::measure($intersection); |
Copybara bot | be50d49 | 2023-11-30 00:16:42 +0100 | [diff] [blame] | 52 | } |
| 53 | } |