Created
November 25, 2015 19:39
-
-
Save matchilling/e6e4490b1fff6a164c2b to your computer and use it in GitHub Desktop.
Find elements in an sorted array $a with a specific distance $k [recursive version]
This file contains hidden or 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
/** | |
* Find elements in an sorted array $a with a specific distance $k | |
* | |
* @param integer $k | |
* @param array $a | |
* @param integer $i | |
* @param integer $j | |
* @return array | |
*/ | |
public static function recfindElementsByDistance($k, array $a = [], $i = 0, $j = 1) | |
{ | |
$length = count($a); | |
if ($i >= $length || $j >= $length) | |
{ | |
return []; | |
} | |
elseif ($k === $a[$j] - $a[$i]) | |
{ | |
return [ | |
$i => $a[$i], | |
$j => $a[$j] | |
]; | |
} | |
else if ($a[$j] - $a[$i] < $k) | |
{ | |
$j ++; | |
return self::recfindElementsByDistance($k, $a, $i, $j); | |
} | |
else | |
{ | |
$i ++; | |
return self::recfindElementsByDistance($k, $a, $i, $j); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment