Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How random is PHP's shuffle function?

Does anyone know what's the randomness of PHP's shuffle() function? Does it depend on the operating system? Does it use PHP's own seeder?

Is it possible to use mt_rand() as generator?

like image 203
Sinan Avatar asked Apr 17 '11 15:04

Sinan


2 Answers

shuffle() function is based on the same generator as rand(), which is the system generator based on linear congruential algorithm. This is a fast generator, but with more or less randomness. Since PHP 4.2.0, the random generator is seeded automatically, but you can use srand() function to seed it if you want.

mtrand() is based on Mersenne Twister algorithm, which is one of the best pseudo-random algorithms available. To shuffle an array using that generator, you'd need to write you own shuffle function. You can look for example at Fisher-Yates algorithm. Writing you own shuffle function will yield to better randomness, but will be slower than the builtin shuffle function.

like image 121
Charles Brunet Avatar answered Oct 11 '22 13:10

Charles Brunet


Based on Mirouf's answer (thank you so much for your contribution)... I refined it a little bit to take out redundant array counting. I also named the variables a little differently for my own understanding.

If you want to use this exactly like shuffle(), you could modify the parameter to be passed by reference, i.e. &$array, then make sure you change the return to simply: "return;" and assign the resulting random array back to $array as such: $array = $randArr; (Before the return).

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));
    }

    return $randArr;
}
like image 44
KDallas Avatar answered Oct 11 '22 13:10

KDallas