Skip to content

Commit 8012cfb

Browse files
authored
Merge pull request #1 from dan-on/intersection-iterators
Intersection iterators
2 parents c514568 + bf64aa7 commit 8012cfb

9 files changed

+1955
-225
lines changed

README.md

+24-21
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
# 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.
33

44
## Usage
55

@@ -10,27 +10,30 @@ require_once 'vendor/autoload.php';
1010
use Danon\IntervalTree\IntervalTree;
1111

1212
$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
1616
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();
1825
}
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
1935

2036
// 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+
```

composer.json

+3
Original file line numberDiff line numberDiff line change
@@ -16,5 +16,8 @@
1616
},
1717
"require": {
1818
"php": "^5.3 || ^7.0"
19+
},
20+
"require-dev": {
21+
"phpunit/phpunit": "^9"
1922
}
2023
}

0 commit comments

Comments
 (0)