我正在寻找一个函数,我可以在 PHP 中传递一个数组和一个种子并取回一个“随机”数组。如果我再次传递相同的数组和相同的种子,我将得到相同的输出。
我试过这段代码
//sample array $test = array(1,2,3,4,5,6); //show the array print_r($test); //seed the random number generator mt_srand('123'); //generate a random number based on that echo mt_rand(); echo "\n"; //shuffle the array shuffle($test); //show the results print_r($test);
但它似乎不起作用。对最好的方法有什么想法吗?
这个问题绕着这个问题跳舞,但它已经过时了,没有人提供关于如何做到这一点的实际答案:Can i randomize an array by providing a seed and get the same order? - "is" - 但如何?
更新
到目前为止,答案适用于 PHP 5.1 和 5.3,但不适用于 5.2。恰好我要运行它的机器使用的是 5.2。
谁能在不使用 mt_rand 的情况下举个例子?它在 php 5.2 中被“破坏”了,因为它不会基于相同的种子给出相同的随机数序列。见 php mt_rand page和 bug tracker了解这个问题。
最佳答案
Sorry, but accordingly to the documentation the shuffle function is seeded automatically.
通常,您不应该尝试提出自己的算法来随机化事物,因为它们很可能存在偏见。 Fisher-Yates algorithm众所周知,它既高效又不偏不倚:
function fisherYatesShuffle(&$items, $seed)
{
@mt_srand($seed);
for ($i = count($items) - 1; $i > 0; $i--)
{
$j = @mt_rand(0, $i);
$tmp = $items[$i];
$items[$i] = $items[$j];
$items[$j] = $tmp;
}
}
示例(PHP 5.5.9):
php > $original = array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
php > $shuffled = (array)$original;
php > fisherYatesShuffle($shuffled, 0);
php > print_r($shuffled);
Array
(
[0] => 6
[1] => 0
[2] => 7
[3] => 2
[4] => 9
[5] => 3
[6] => 1
[7] => 8
[8] => 5
[9] => 4
)
php > $shuffled = (array)$original;
php > fisherYatesShuffle($shuffled, 0);
php > print_r($shuffled);
Array
(
[0] => 6
[1] => 0
[2] => 7
[3] => 2
[4] => 9
[5] => 3
[6] => 1
[7] => 8
[8] => 5
[9] => 4
)
关于php - 用种子随机化 PHP 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6557805/