1
1
# PHP Interval tree
2
- Is an implementation of interval binary search tree according to Thomas H. Cormen book "Introduction to Algorithms" .
2
+ Implementation of interval binary search tree.
3
3
4
4
## Usage
5
5
@@ -10,27 +10,30 @@ require_once 'vendor/autoload.php';
10
10
use Danon\IntervalTree\IntervalTree;
11
11
12
12
$tree = new IntervalTree();
13
- $intervals = [[6,8],[1,4],[2,3],[5,12],[1,1],[3,5],[5,7]];
14
-
15
- // Insert interval as a key and string "val0", "val1" etc. as a value
13
+ $intervals = [[6, 8], [1, 4], [2, 3], [5, 12], [1, 1], [3, 5], [5, 7]];
14
+
15
+ // Insert interval as a key and interval index as a value
16
16
for ($i=0; $i < count($intervals); $i++) {
17
- $tree->insert($intervals[$i], "val" . $i);
17
+ $tree->insert($intervals[$i], $i);
18
+ }
19
+
20
+ // Iterate nodes which keys intersect with given interval
21
+ $nodesInRange = $tree->iterateIntersections([2, 3]);
22
+ $intersectedIntervalIndexes = [];
23
+ foreach ($nodesInRange as $node) {
24
+ $intersectedIntervalIndexes[] = $node->getValue();
18
25
}
26
+ // Expected array: [1, 2, 5]
27
+
28
+ // Check that interval has at least one intersection
29
+ $tree->hasIntersection([2, 3]);
30
+ // Expected value: true
31
+
32
+ // Count intervals that has intersections
33
+ $tree->countIntersections([2, 3]);
34
+ // Expected value: 3
19
35
20
36
// Get array of keys sorted in ascendant order
21
- $sorted_intervals = $tree->getKeys(); // expected array [[1,1],[1,4],[5,7],[5,12],[6,8]]
22
-
23
- // Search items which keys intersect with given interval, and return array of values
24
- $valuesInRange = $tree->search([2,3], function($value, $key) {
25
- return $value;
26
- });
27
-
28
- print_r($valuesInRange);
29
-
30
- // Array
31
- // (
32
- // [0] => val1
33
- // [1] => val2
34
- // [2] => val5
35
- // )
36
- ```
37
+ $sortedIntervals = $tree->getKeys();
38
+ // Expected array: [[1, 1], [1, 4], [2, 3], [3, 5], [5, 7], [5, 12], [6, 8]]
39
+ ```
0 commit comments