Skip to content

Instantly share code, notes, and snippets.

@codelikesuraj
Created May 15, 2021 08:03
Show Gist options
  • Save codelikesuraj/9ba05b483b8c6886ea5011aba20d47c5 to your computer and use it in GitHub Desktop.
Save codelikesuraj/9ba05b483b8c6886ea5011aba20d47c5 to your computer and use it in GitHub Desktop.
Solution to "Algorithm Fridays (14-05-2021)" problem
<?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;
}
?>
@meekg33k
Copy link

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:

  • When num_of_stud has a value greater than the size of the input_array list. For such cases, your solution returns FALSE 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 of num_of_stud is greater than the size of input_array, you should think of it as shuffling the entire pupils list for as many times as is possible until num_of_stud becomes less than the size of input_array. In mathematical terms, that would be num_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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment