I am currently working on project and it requires to arrange an array such that no same numbers come consecutively.
Let $a = [4,1,2,1,3,4,4,4], here the numbers 4 come consecutively. I need to avoid that and the desired output must be or simiar to $a = [4,1,4,1,4,2,3,4]
What i had done:
$a=[4,1,2,1,3,4,4,4];
for($i=0;$i<count($a)-1;$i++)
{
if($a[$i]==$a[$i+1])
{
$k=$j=$i+1;
while($a[$j]==$a[$k])
{
$k++;
if($k >= count($a))
$k=0;
}
$temp=$a[$j];
$a[$j]=$a[$k];
$a[$k]=$temp;
}
}
var_dump($a);
Outputs:
array (size=8)
0 => int 4
1 => int 4
2 => int 2
3 => int 1
4 => int 3
5 => int 4
6 => int 1
7 => int 4
Here 4 comes again consecutively.
Is there a simple way to achieve this? Please help me to resolve this situation.
Thanks in advance.