从数组中选择随机值时,请确保两个特定值不会相邻出现


when selecting random values from arrays, make sure two certain ones do not appear next to each other

我有一个包含18个值的数组,我使用$array[rand(0,17)]从中选择随机值。我把这些随机选择的值放在页面上。数组中有6组值,我不想把它们放在页面上。有没有什么方法可以让我检测出这对何时在一起,并因为而选择新的值

警告:你确定不会得到任何退化的情况吗?例如,如果你不允许对[1,2]或[2,1],而你得到的数组是[1,1,1,11,1,12,2,2,20,2,22,2,23,23,22,23,24,24,25,25,27,27,28,28,26,28,27,30,28,30,30,32,30,31,32,32,31,31,42,32。没有办法以您想要的方式显示数组,而且像我下面描述的方法永远不会终止。


我会使用shuffle($array),然后一次迭代一个打乱的数组,以找出是否有任何值与之前的项"不兼容"。如果是,只需重新排列数组,然后重试。你无法预测需要多少次尝试才能得到一个有效的洗牌数组,但所需的时间应该可以忽略不计。

为了检测两个值是否兼容,我建议创建一个包含所有不兼容对的数组。例如,如果你不想有连续的对1和3或2和5,那么你的数组将是:

$incompatible = array(
    array(1,3),
    array(2,5) );

然后,你可以用类似于的东西迭代你的搅乱数组

for ($i=1; i<count($array)-1; i++;) {
    $pair = $array[i, i+1]; // this is why the for loop only goes to the next-to-last item
    if in_array($pair, $incompatible) { 
        // you had an incompatible pair in your shuffled array.
        // break out of the for loop, re-sort your array, and try again.
    }
} 
// if you get here, there were no incompatible pairs
// so go ahead and print the shuffled array!

或者与unset()一起使用以移除密钥,或者由Session使用以进行下一次跳过。