Created
January 28, 2013 04:23
-
-
Save nonakap/4653015 to your computer and use it in GitHub Desktop.
Marzullo's algorithm
based on https://gist.github.com/3684493
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Marzullo's algorithm | |
* | |
* @see http://en.wikipedia.org/wiki/Marzullo%27s_algorithm | |
* @see https://gist.github.com/3684493 | |
*/ | |
function marzullo_algorithm($ranges) | |
{ | |
$table = array(); | |
foreach ($ranges as $range) { | |
$table[] = array($range[0], -1); | |
$table[] = array($range[1], +1); | |
} | |
usort($table, function($lhs, $rhs) { | |
$result = intval($lhs[0]) - intval($rhs[0]); | |
if ($result === 0) { | |
$result = intval($rhs[1]) - intval($lhs[1]); // to exclude 'pathological overlaps' | |
} | |
return $result; | |
}); | |
$best = 0; | |
$count = 0; | |
$len = count($table) - 1; | |
for ($i = 0; $i < $len; $i++) { | |
$count = $count - $table[$i][1]; | |
if ($best < $count) { | |
$best = $count; | |
$beststart = $table[$i][0]; | |
$bestend = $table[$i + 1][0]; | |
} | |
} | |
return array($best, $beststart, $bestend); | |
} | |
function test($tests) { | |
foreach ($tests as $test) { | |
$result = marzullo_algorithm($test['input']); | |
if ($result == $test['expected']) { | |
echo "Test OK\n"; | |
} else { | |
echo 'Test failed: input=' . print_r($test['input']) . ', expected=' . print_r($test['expected']) . ', actual=' . print_r($result) . "\n"; | |
} | |
} | |
} | |
$test_data = [ | |
['input' => [[8,12],[11,13],[10,12]], 'expected' => [3,11,12]], | |
['input' => [[8,12],[11,13],[14,15]], 'expected' => [2,11,12]], | |
['input' => [[8,9],[8,12],[10,12]], 'expected' => [2,8,9]], | |
['input' => [[8,12],[9,10],[11,13],[10,12]], 'expected' => [3,11,12]], | |
['input' => [[8,12],[9,10],[11,13],[14,15]], 'expected' => [2,9,10]], | |
['input' => [[11,15],[8,15],[9,11],[10,14],[11,14],[9,10],[9,13],[12,15],[8,11],[14,15]], 'expected' => [6,12,13]], | |
]; | |
test($test_data); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment