0

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.

4
  • is it ok in your question "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]" Commented Apr 20, 2016 at 8:01
  • why don't you find duplicates first and embed distinct elements in between? Commented Apr 20, 2016 at 8:02
  • @BrijalSavaliya i did not understand what u commented. That array will be input and i have to arrange such that no same numbers consecutively. Commented Apr 20, 2016 at 8:04
  • @raptor96 that array is the result of random numbers (from another function) and could not change that Commented Apr 20, 2016 at 8:07

1 Answer 1

2

Try this -

$a=[4,1,2,1,3,4,4,4];
$n = count($a);
for($k=0;$k<$n;$k++)
{
  for($i=0;$i<$n-1;$i++)
  {
          if($a[$i]==$a[$i+1])
          {   
                  $cir = ($i+$k)%$n;
                  $temp=$a[$i+1];
                  $a[$i+1]=$a[$cir];
                  $a[$cir]=$temp;
          }
  }
}
var_dump($a);
Sign up to request clarification or add additional context in comments.

3 Comments

+1 for you because it works all the time. But may i point out that if a number is present more than $n/2 times the solution does not exist while your code still outputs something? (something wrong of course)
Yes I noted that case, it will need to be handled explicitly. Thanks though.
Perfect, Thanks a lot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.