簡體   English   中英

PHP:如何創建唯一的有序列表?

[英]PHP: How to create a unique ordered list?

這是一個游戲。 我有一個包含52個元素的數組。 我希望每次都能創建這些元素的唯一列表,但不想使用隨機化,因為這樣做會冒着在序列的開頭或結尾使前幾個元素和最后一個元素相同的風險。

我在想,如果不使用真正的隨機列表,該如何處理。 所以我想,如果我開始使用隨機列表為列表添加種子,然后每次之后,它都會執行一種獨特的排序列表的方法,因此,盡管它看起來是隨機的,但不會重復前幾個和最后一個元素。

因此,我正在考慮的一種方法是從隨機列表的中間開始,然后向上移動一個元素並向下移動一個元素以創建列表的新順序。 然后在此之后每次都進行相同的改組,因為缺少更好的術語。

還有其他可能流行的方法,但我沒有考慮嗎?

我開始用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);

一個簡單的示例是一個由52個元素組成的數組,它們的編號從1到52。它從中間開始,上移一個,下移一個。 因此1 = 26、2 = 27、3 = 25、4 = 28、5 = 24、6 = 29、7 = 23等

$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重新開始。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM