Skip to content

Commit

Permalink
Merge pull request #1 from dan-on/intersection-iterators
Browse files Browse the repository at this point in the history
Intersection iterators
  • Loading branch information
dan-on committed Apr 1, 2020
2 parents c514568 + bf64aa7 commit 8012cfb
Show file tree
Hide file tree
Showing 9 changed files with 1,955 additions and 225 deletions.
45 changes: 24 additions & 21 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# PHP Interval tree
Is an implementation of interval binary search tree according to Thomas H. Cormen book "Introduction to Algorithms".
Implementation of interval binary search tree.

## Usage

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

$tree = new IntervalTree();
$intervals = [[6,8],[1,4],[2,3],[5,12],[1,1],[3,5],[5,7]];

// Insert interval as a key and string "val0", "val1" etc. as a value
$intervals = [[6, 8], [1, 4], [2, 3], [5, 12], [1, 1], [3, 5], [5, 7]];
// Insert interval as a key and interval index as a value
for ($i=0; $i < count($intervals); $i++) {
$tree->insert($intervals[$i], "val" . $i);
$tree->insert($intervals[$i], $i);
}

// Iterate nodes which keys intersect with given interval
$nodesInRange = $tree->iterateIntersections([2, 3]);
$intersectedIntervalIndexes = [];
foreach ($nodesInRange as $node) {
$intersectedIntervalIndexes[] = $node->getValue();
}
// Expected array: [1, 2, 5]

// Check that interval has at least one intersection
$tree->hasIntersection([2, 3]);
// Expected value: true

// Count intervals that has intersections
$tree->countIntersections([2, 3]);
// Expected value: 3

// Get array of keys sorted in ascendant order
$sorted_intervals = $tree->getKeys(); // expected array [[1,1],[1,4],[5,7],[5,12],[6,8]]

// Search items which keys intersect with given interval, and return array of values
$valuesInRange = $tree->search([2,3], function($value, $key) {
return $value;
});

print_r($valuesInRange);

// Array
// (
// [0] => val1
// [1] => val2
// [2] => val5
// )
```
$sortedIntervals = $tree->getKeys();
// Expected array: [[1, 1], [1, 4], [2, 3], [3, 5], [5, 7], [5, 12], [6, 8]]
```
3 changes: 3 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,8 @@
},
"require": {
"php": "^5.3 || ^7.0"
},
"require-dev": {
"phpunit/phpunit": "^9"
}
}
Loading

0 comments on commit 8012cfb

Please sign in to comment.