PHP的洗牌功能有多随机?

2022-08-30 23:07:21

有谁知道PHP函数的随机性是什么?这取决于操作系统吗?它是否使用PHP自己的播种机?shuffle()

是否可以用作发电机?mt_rand()


答案 1

shuffle()函数基于与 相同的生成器,即基于线性同余算法的系统生成器。这是一个快速的生成器,但或多或少具有随机性。从 PHP 4.2.0 开始,随机生成器是自动设定种子的,但如果需要,您可以使用函数来设定种子。rand()srand()

mtrand()基于Mersenne Twister算法,这是最好的伪随机算法之一。要使用该生成器对数组进行随机排序,您需要编写自己的随机播放函数。例如,您可以查看Fisher-Yates算法。编写自己的洗牌函数将产生更好的随机性,但会比内置的洗牌函数慢。


答案 2

根据米鲁夫的回答(非常感谢你的贡献)...我对它进行了一些改进,以消除冗余数组计数。为了我自己的理解,我也以不同的方式命名了变量。

如果你想像shuffle()一样使用它,你可以修改要通过引用传递的参数,即&$array,然后确保将返回更改为简单地:“return;”,并将生成的随机数组赋回$array,如下所示:$array = $randArr;(返回前)。

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

推荐