请确保相同的数组项在php中彼此不相邻

问题描述 投票:1回答:1

我正在为这个案子苦苦挣扎。我有一个随机数组,类似的项目可以彼此相邻,但我不希望它发生。

示例:

array("red","red","blue","green","green","blue");

Expected Output : array("red","blue","red","green","blue","green")

所以我一直在考虑将这些项目改组,直到彼此之间没有相似的项目为止。但是,如果数组具有很多值,则会花费很多时间。

有没有有效的方法来实现它?

任何帮助将不胜感激。谢谢

php arrays shuffle
1个回答
0
投票

只是一个想法:随机播放原始数组。比较前两个。如果它们相同,则将第二个与最后一个交换。移至下一对,依此类推。

在这里,我们假设最坏的情况是混洗,其下一个值相同。

$colors = ["red", "red", "blue", "green", "green", "blue"];

for($i = 0; $i < count($colors)-1; $i++) {
    if($colors[$i] === $colors[$i+1]) {
        $last = $colors[count($colors)-1];
        $colors[count($colors)-1] = $colors[$i];
        $colors[$i+1] = $last;
    }
}

print_r($colors);

Array
(
    [0] => red
    [1] => blue
    [2] => red
    [3] => green
    [4] => blue
    [5] => green
)
© www.soinside.com 2019 - 2024. All rights reserved.