Created
November 4, 2016 09:17
-
-
Save kdallas/7717e814635bffe8b3725724d0cef140 to your computer and use it in GitHub Desktop.
A substitute for the php shuffle() function using mt_rand(), i.e. the Mersenne Twister algorithm - for improved randomness
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 mt_shuffle(&$array) { | |
$randArr = []; | |
$arrLength = count($array); | |
// while my array is not empty I select a random position | |
while (count($array)) { | |
//mt_rand returns a random number between two values | |
$randPos = mt_rand(0, --$arrLength); | |
$randArr[] = $array[$randPos]; | |
/* If number of remaining elements in the array is the same as the | |
* random position, take out the item in that position, | |
* else use the negative offset. | |
* This will prevent array_splice removing the last item. | |
*/ | |
array_splice($array, $randPos, ($randPos == $arrLength ? 1 : $randPos - $arrLength)); | |
} | |
$array = $randArr; | |
return; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment