How random is PHP's shuffle function?

后端 未结 7 1955
眼角桃花
眼角桃花 2020-12-03 21:12

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 poss

7条回答
  •  自闭症患者
    2020-12-03 21:44

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

提交回复
热议问题