2013-04-27 42 views
0

這是一款遊戲。我有一個包含52個元素的數組。我希望能夠每次創建這些元素的唯一列表,但不希望使用隨機化,因爲它可能會在序列的開始或結束時使前幾個元素和最後一個元素相同。PHP:如何創建一個唯一的有序列表?

我想,如果沒有使用真正的隨機列表我怎麼能處理這個。所以我想,如果我開始用一個隨機列表開始排序列表,然後每次都會有一個排序列表的獨特方法,那麼雖然它看起來是隨機的,但它不會重複前幾個和最後的元素。

所以一個方法,我考慮的是在隨機列表的中間開始和一個元素和下一個元素上創建列表的新秩序。然後,每次之後,都會因缺乏更好的術語而進行相同的洗牌。

還有沒有其他的方法來這樣做,可能是受歡迎的,但我不考慮?

我開始在PHP寫這一點,但我的代碼是行不通的。不知道我在做什麼錯誤,所以如果你覺得這是一個很好的排序方法,即使我的PHP代碼不工作,你也可以評論一下。謝謝!

// First create an array of 52 elements, numbered 1…52. 
for ($number=1; $number<=52; $number++) 
    { 
    $sequential_list[$number] = $number; 
    } 

print_r($sequential_list); 

// Find the middle of $sequential_list 

$middle = 26; 

// Set the $middle as the first element in the new_list to seed it. 
// Now go up one and down one from the $middle 
    $new_list[1] = $sequential_list[$middle]; 
    $up = $middle; 
    $down = $middle; 
$index = 2; 

while ($index<=52) 
    { 
    $new_list[$index] = $sequential_list[$up++]; 
    echo "up is: " . $up . "\n"; 
    $new_list[$index++] = $sequential_list[$down--]; 
    } 

print_r($new_list); 

一個簡單的例子是,其編號爲1至52,將在中間開始,上去一個和向下一個52個元件的陣列。使得 1 = 26,2 = 27,3 = 25,4 = 28,5 = 24,6 = 29,J = 23等

+1

[洗牌](http://www.php.net/manual/en/function.shuffle.php)? – 2013-04-27 22:50:02

+0

隨機洗牌,如洗牌遊戲一樣。 – Edward 2013-04-27 22:51:57

+0

請點擊鏈接:-) – 2013-04-27 22:53:57

回答

1
$middle = rand(5,47);//as not to get the first and last five elements int the same order 

$first = array_slice($sequential_list, 0, $middle); 
$second = array_slice($sequential_list, $middle); 

shuffle($first); 
shuffle($second); 

$random_list = array_merge($second, $first); 

對於下一迭代你從新重新開始random_list。

+0

謝謝!我相信這對我的問題是一個可行的解決方案。 – Edward 2013-04-27 23:53:38

相關問題