Created
May 15, 2021 08:03
-
-
Save codelikesuraj/9ba05b483b8c6886ea5011aba20d47c5 to your computer and use it in GitHub Desktop.
Solution to "Algorithm Fridays (14-05-2021)" problem
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 | |
function shuffleClass($input_array, $num_of_stud){ | |
if (is_array($input_array) && count($input_array)>2 && is_integer($num_of_stud) && abs($num_of_stud) <= count($input_array)): | |
// number is negative | |
if ($num_of_stud < 0): | |
for($i=0; $i<abs($num_of_stud); $i++){ | |
$array1[] = $input_array[$i]; | |
} | |
$array2 = array_diff($input_array, $array1); | |
return array_merge($array2, $array1); | |
// number is positive | |
elseif ($num_of_stud > 0): | |
for($i=count($input_array)-$num_of_stud; $i<count($input_array); $i++){ | |
$array1[] = $input_array[$i]; | |
} | |
$array2 = array_diff($input_array, $array1); | |
return array_merge($array1, $array2); | |
else: | |
return $input_array; | |
endif; | |
else: | |
return 'FALSE'; | |
endif; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello @codelikesuraj, thank you for participating in Week 6 of #AlgorithmFridays.
This is a decent attempt at coming up with a solution for Apex College. Your solution works for most test cases and you demonstrated good knowledge of PHP in-built functions.
However, one test case your solution didn't pass is:
num_of_stud
has a value greater than the size of theinput_array
list. For such cases, your solution returnsFALSE
because of your check on line 26. For example,shuffleClass([2, 3], 3); // yours would return FALSE instead of [3, 2]
. The expectation is that when the value ofnum_of_stud
is greater than the size ofinput_array
, you should think of it as shuffling the entire pupils list for as many times as is possible untilnum_of_stud
becomes less than the size ofinput_array
. In mathematical terms, that would benum_of_stud = num_of_stud % input_array.length
.I understand that your solution was made with a lot of assumptions of how certain things should be implemented but I think it's always best to check in with your interviewer before making assumptions. I wrote about that in this article, you might find it helpful.
Please let me know your thoughts.