可以在种子洗牌被逆转? [英] Can a seeded shuffle be reversed?
问题描述
取本功能,这是一个引晶费雪耶茨洗牌(顺序是随机的,但可再现给定相同的种子):
Take this function, which is a seeded Fisher-Yates shuffle (the order is random, but reproducible given the same seed):
function seeded_shuffle(array &$items, $seed = false) {
$items = array_values($items);
mt_srand($seed ? $seed : time());
for ($i = count($items) - 1; $i > 0; $i--) {
$j = mt_rand(0, $i);
list($items[$i], $items[$j]) = array($items[$j], $items[$i]);
}
}
能否这种算法被逆转?即,由于种子值和洗牌阵列,可以在阵列是unshuffled到其原来的顺序?如果是这样,怎么样?
Can this algorithm be reversed? I.e., given the seed value and the shuffled array, can the array be "unshuffled" into its original order? If so, how?
(这个问题上来<一个href=\"http://stackoverflow.com/questions/19658239/generate-$p$pdictable-suffled-random-array/19658344#comment37472805_19658344\">in这里的意见。)
(The question came up in the comments here.)
推荐答案
原来,答案是肯定的,而且pretty简单:
Turns out the answer is yes, and pretty simple:
function seeded_unshuffle(array &$items, $seed) {
$items = array_values($items);
mt_srand($seed);
$indices = [];
for ($i = count($items) - 1; $i > 0; $i--) {
$indices[$i] = mt_rand(0, $i);
}
foreach (array_reverse($indices, true) as $i => $j) {
list($items[$i], $items[$j]) = [$items[$j], $items[$i]];
}
}
只要使用公知的种子产生相同的随机数序列,并在反向遍历它
Just generate the same random number sequence using the known seed, and traverse it in reverse.
这篇关于可以在种子洗牌被逆转?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!