Created
September 4, 2015 06:56
-
-
Save kapolos/85ed05c31340714c9f88 to your computer and use it in GitHub Desktop.
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
/** | |
* Checks if the sum of any 2 values of the array equals to $sum | |
* Assumes a non-associative array with numeric values | |
* | |
* @param array $arr | |
* @param integer $sum | |
* | |
* @return bool | |
*/ | |
function checkSumExists(array $arr, $sum) | |
{ | |
sort($arr, SORT_NUMERIC); | |
$topdown = 0; | |
$downup = count($arr) - 1; | |
while ($topdown < $downup) { | |
$step = $arr[$topdown] + $arr[$downup]; | |
switch (TRUE) { | |
case ($step == $sum): | |
return TRUE; | |
break; | |
case ($step < $sum): | |
$topdown++; | |
break; | |
case ($step > $sum): | |
$downup++; | |
break; | |
} | |
} | |
return FALSE; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment