正常洗牌可以實現同樣
接他們
我們可以調整滴落步驟,將每個元素都放到整個範圍內,但是在某些位置ding窗口。假設N
是數組中元素的數量,窗口寬度將是w
,我們將在每個步驟將其移動off
。然後off*(N-1) + w
將是範圍的總寬度。
這是一個函數,它扭曲元素的位置,但不是完全隨機的。
function weak_shuffle($a, $strength) {
$len = count($a);
if ($len <= 1) return $a;
$out = array();
$M = mt_getrandmax();
$w = round($M/($strength + 1)); // width of the sliding window
$off = ($M - $w)/($len - 1); // offset of that window for each step.
for ($i = 0; $i < $len; $i++) {
do {
$idx = intval($off * $i + mt_rand(0, $w));
} while(array_key_exists($idx, $out));
$out[$idx] = $a[$i];
}
ksort($out);
return array_values($out);
}
$strength = 0
〜正常洗牌。
$strength = 0.25
〜你想要的結果(40.5%,25.5%,22%,爲elephant
12%)
$strength = 1
第一個項目將永遠最後一個之後。
$strength >= 3
陣列實際上從來沒有洗牌
遊樂場來進行測試:
$animals = array('elephant', 'dog', 'cat', 'mouse');
$pos = array(0,0,0,0);
for ($iter = 0; $iter < 100000; $iter++) {
$shuffled = weak_shuffle($animals, 0.25);
$idx = array_search('elephant', $shuffled);
$pos[$idx]++;
}
print_r($pos);
一個有趣的問題,但是爲結束在每個位置的每個元素分配概率的機制是刑事規定不足的。 – Jon 2012-03-21 19:33:04
例如10%以下會發生什麼? – Cyclone 2012-03-21 19:35:18
在這種情況下,大象有10%的機會在最後的位置,90%的機會不在最後的位置。 – 2012-03-21 19:46:39