2012-11-24 43 views
1

我希望有人可以幫助我這個。我想採取一個有序的php數組,並隨意「晃動」一下來改變順序,但保留一些原始的整體結構。部分隨機化的PHP數組

想象一下,你有一盤彩色亮片組成一張房子的照片。如果你稍微晃動一下托盤,亮片就會移動,但是,根據你搖晃多少,你仍然會保留一些房子的原始結構 - 它會變得更模糊。這就是我想用php數組做的事情。

讓我舉個例子。假設我有以下數組:

$Array=Array(
    1=>15, 
    2=>14, 
    3=>13, 
    4=>12, 
    5=>11, 
    6=>10, 
    7=>9, 
    8=>8, 
    9=>7, 
    10=>6, 
    11=>5, 
    12=>4, 
    13=>3, 
    14=>2, 
    15=>1); 

我希望能夠搖晃它約一點給類似:

$Array=Array(
    1=>13, 
    2=>15, 
    3=>12, 
    4=>14, 
    5=>11, 
    6=>8, 
    7=>7, 
    8=>10, 
    9=>5, 
    10=>6, 
    11=>9, 
    12=>4, 
    13=>2, 
    14=>1, 
    15=>3); 

訂單已部分隨機的,但是從15普遍呈下降趨勢到1仍然。我希望這是有道理的。

除非我錯了,我不認爲有一個本地函數在PHP中這樣做。但有人知道這可以實現嗎?

+0

也許你可以用'array_shuffle'和'array_values'做些什麼 –

回答

6

,而不是使用功能,如shuffle()array_shuffle()被優化,得到的結果儘可能多shuffeled儘可能你應該寫自己的算法:

有一個「冒泡」戰略的一個嘗試:

  • 通過交換對來交換數組的元素,一對接一個。
  • 始終從數組中選取相鄰元素作爲成對。
  • 隨機選擇您爲每個迭代步驟選擇的現有對。
  • 您可以限制迭代次數,從而限制結果的總「混洗」。

這應該比嚴格的隨機化更好地保留元素的粗略位置,因爲元素只能在每次迭代中移動一步。所以總的趨勢應該保留。多少取決於您執行的迭代次數。

這裏是一個(很簡單)示例實現:

#!/usr/bin/php 
<?php 

// the input array, just as you specified it 
$input=array(
    1=>15, 
    2=>14, 
    3=>13, 
    4=>12, 
    5=>11, 
    6=>10, 
    7=>9, 
    8=>8, 
    9=>7, 
    10=>6, 
    11=>5, 
    12=>4, 
    13=>3, 
    14=>2, 
    15=>1 
); 

// the algorithm itself, a 'bubbling' function 
function array_bubble (&$collection, $limit) { 
    for ($i=1; $i<=$limit; $i++) { 
     $pos=rand(min(1,sizeof($collection)-1); 
     $help=$collection[$pos]; 
     $collection[$pos] =$collection[$pos+1]; 
     $collection[$pos+1]=$help; 
    } 
    return $collection; 
} // function array_bubble 

// here the algorithm is called and the result printed 
// note that the '20' in there is the number of iterations. Try changing it! 
print_r(array_bubble($input,20)); 

?> 

該腳本會產生這樣的輸出:

Array 
(
    [1] => 11 
    [2] => 15 
    [3] => 13 
    [4] => 8 
    [5] => 14 
    [6] => 12 
    [7] => 9 
    [8] => 10 
    [9] => 5 
    [10] => 6 
    [11] => 7 
    [12] => 4 
    [13] => 1 
    [14] => 3 
    [15] => 2 
) 
+0

謝謝。看起來不錯。我會試試這個。 – animal

+0

隨着一些調整,我已經完成了我所需要的。謝謝你的時間。非常感激。 – animal

+1

你喜歡分享,這樣別人也可以學習嗎?你調整了什麼? – arkascha

1

由arkascha提到的冒泡的戰略替代方案,您可以遍歷該數組,並生成一個高斯/正態分佈的隨機數來交換當前元素。也許更好地描述在代碼(未經測試):

function swap (&$arr, $a, $b) { 
    $tmp=$arr[$a]; 
    $arr[$a]=$arr[$b]; 
    $arr[$b]=$tmp; 
} 
for ($i = 0; $i < count($arr); $i++) { 
    $diff = round(stats_rand_gen_normal(0, 3)); 
    $j = max(0, min(count($arr), $i + $diff)); 
    swap($arr, $i, $j); 
} 

這應該只需要一次;抖動的均值和標準偏差應大致爲stats_rand_gen_normal的參數。

+0

聰明的做法。感謝您花時間回答這個問題。 – animal