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

时间:2013-04-27 22:40:04

标签: php

这是一场比赛。我有一个包含52个元素的数组。我希望每次都能够创建这些元素的唯一列表,但不希望使用随机化,因为它存在使序列的开头或结尾的前几个和最后一个元素相同的风险。 / p>

我在想如果不使用真正的随机列表,我怎么能接近这个。所以我想,如果我开始使用随机列表对列表进行播种,那么每次之后它都会使用一种独特的方法对列表进行排序,所以虽然它看起来是随机的,但它不会复制前几个和最后的元素。

所以我正在考虑的一个方法是从随机列表的中间开始,然后向上移动一个元素并向下移动一个元素以创建列表的新顺序。然后每次在那之后,由于缺乏一个更好的术语,做同样的改组。

还有其他方法可以做到这一点,但我不考虑吗?

我开始用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等。

1 个答案:

答案 0 :(得分: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重新开始。