Created
August 16, 2013 00:55
-
-
Save RavenHursT/6246341 to your computer and use it in GitHub Desktop.
Test question for Gumroad
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 | |
// 1, 4, 6, 3, 2 | |
function findPivot($arr, $checkIndex = NULL){ | |
//if only one value is passed into array, that is the pivot point because nothing on the left == nothing on the right | |
if(count($arr) == 1) return 0; | |
$lastCheckIndex = count($arr) - 1; | |
if( | |
$checkIndex > $lastCheckIndex || | |
( | |
$checkIndex == $lastCheckIndex && | |
array_sum(array_slice($arr, 0, $checkIndex)) != array_sum(array_slice($arr, $checkIndex + 1)) | |
) | |
){ | |
return -1; | |
} | |
if(!$checkIndex){ | |
return findPivot($arr, 1); | |
} elseif(array_sum(array_slice($arr, 0, $checkIndex)) != array_sum(array_slice($arr, $checkIndex + 1))){ | |
return findPivot($arr, $checkIndex + 1); | |
} else { | |
return $checkIndex; | |
} | |
} | |
var_dump(findPivot(array(1, 4, 6, 3, 2))); | |
die('done.' . PHP_EOL); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment