问题描述
如何使php shuffle函数使用种子,以便当我使用相同的种子时,shuffle函数将输出相同的数组.我读到随机播放是自动播种的.有没有办法使用该混洗的种子,或者如何使用自定义种子创建/模拟混洗?
How can I make the php shuffle function use a seed, so that when I use the same seed, the shuffle function will output the same array. I read that shuffle is automatically seeded. Is there a way to get the seed of that shuffle used, or how can I create/mimic shuffle with a custom seed?
推荐答案
您无法检索shuffle使用的种子,但是可以模拟shuffle并修复自己的种子:
You can't retrieve the seed used by shuffle, but you can simulate shuffle and fix your own seed:
$array = range(1, 10);
function seededShuffle(array &$array, $seed) {
mt_srand($seed);
$size = count($array);
for ($i = 0; $i < $size; ++$i) {
list($chunk) = array_splice($array, mt_rand(0, $size-1), 1);
array_push($array, $chunk);
}
}
$seed = date('Ymd');
seededShuffle($array, $seed);
var_dump($array);
这将每天设置不同的种子,但是在一天中它将使用相同的种子并以相同的顺序对数组进行随机排序;明天将是与今天不同的随机洗牌
This will set a different seed each day, but throughout the day it will use the same seed and shuffle the array in the same order; tomorrow will be a different random shuffle to today
今天(2015年6月6日),顺序应为
For today (6th June 2015), the sequence should be
3, 6, 9, 2, 7, 1, 8, 5, 10, 4
这篇关于PHP用种子洗牌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!