Last active
September 18, 2017 09:19
-
-
Save Ammly/a08920985ec1108a762014675e5e9880 to your computer and use it in GitHub Desktop.
Php tests
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 | |
/* | |
Challenge #1: | |
Write an algorithm that takes an array and moves all of the zeros to the end, preserving the order of the other elements. | |
moveZeros([false, 1, 0, 1, 2, 0, 1, 3, "a"]) | |
// returns [false, 1, 1, 2, 1, 3, "a", 0, 0] | |
*/ | |
function moveZeros($arr) { | |
$count = 0; | |
$n = sizeof($arr); | |
for ($i = 0; $i < $n; $i++) { | |
if ($arr[$i] != 0) { | |
$arr[$count++] = $arr[$i]; | |
} | |
} | |
// Shift non-zeros to the front | |
while ($count < $n) { | |
$arr[$count++] = 0; | |
} | |
return $arr; | |
} | |
print_r(moveZeros([false, 1, 0, 1, 2, 0, 1, 3, "a"])); |
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 | |
/* | |
Write a function maxPair(A) that takes a list A, and returns the 2 integers in the array, A, that make up a pair with the highest sum. | |
e.g. maxPair([10, 5, 6, 3, 9]) returns [10, 9] or [9, 10] (whichever order) | |
*/ | |
function maxPair($A) { | |
$last = max($A); | |
$second = max(array_diff($A, [$last])); | |
return [$last, $second]; | |
} | |
#test | |
$A = [10, 5, 6, 3, 9]; | |
print_r(maxPair($A)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment