0

这是为了游戏。我有一个包含 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 等等。

4

1 回答 1

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

于 2013-04-27T23:22:51.423 回答