How to rearrange data in array so that two similar items are not next to each other?

后端 未结 8 1891
暗喜
暗喜 2020-12-31 12:00

Just want to rearrange the data in array so that similar items are not next to each. The data should not be removed from the array, if it can\'t be rearranged it can be put

相关标签:
8条回答
  • 2020-12-31 12:25

    In javascript, I'd probably do:

        var arr = [ 1, 1, 1, 2, 3 ];
        var i = 0, len = arr.length;
    
        while (i < len - 1) {
            if (arr[i] == arr[i+1]) {
                //index is equal to it's partner.
                if (arr[i+2] && arr[i] == arr[i+2]) {
                    // 3 equal values in a row, swapping won't help. Need to recheck this index in this case.
                    var tmp = arr[i];
                    arr.splice( i, 1 );
                    arr.push( tmp );
                } else {
                    // Swap the next and 2nd next index.
                    var tmp = arr[i+1];
                    arr[i+1] = arr[i+2];
                    arr[i+2] = tmp;
                    i++;
                }
            } else {
                // this index is fine, move on.
                i++;
            }
        }
    

    This is a quick example, coding style could probably be cleaned up a lot

    0 讨论(0)
  • 2020-12-31 12:29

    Assuming A Array Containing Digits Between 0 To 9:
    Similar To Bucket Sort In A Way

    int B[10];//buckets
    diff=0;//how many different digits appeared
    
    for(i=0;i<A.length;i++)
    {
     x=A[i];
     if(B[x]==0)
     {
      diff++;
     }
     B[x]++;
    }//loaded
    while(diff>=0)//now to place back to array makes an interleaving
    {
     for(digit=0;digit<10;digit++)
     {
      if(B[digit]<>0)
      {
       A[B[digit]+diff]=digit;
       B[digit]--;
      }
     }
     diff--;
    }
    
    0 讨论(0)
提交回复
热议问题