Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 at the end of the array. But keeping the original order is necessary.

Example

   1 1 2             =>   1 2 1 
   1 1 1 2 3         =>   1 2 1 3 1
   1 1 2 1 3 3 5 1   =>   1 2 1 3 1 3 5 1
   1 1 1 1 1 1 2     =>   1 2 1 1 1 1 1
   8 2 1 3 7 2 5     =>   rearrange not needed
   8 2 2 2 7 2 5 2   =>   8 2 7 2 5 2 2      // keep the original order

EDIT: Added example to show keeping original order is needed

like image 211
Mark K Avatar asked Nov 11 '10 17:11

Mark K


People also ask

How do you rearrange elements in an array?

Approach(Naive Approach): Navigate the numbers from 0 to n-1. Now navigate through array. If (i==a[j]) , then replace the element at i position with a[j] position. If there is any element in which -1 is used instead of the number then it will be replaced automatically.

How do you sort an array with repeated elements?

A simple solution would be to use efficient sorting algorithms like Merge Sort, Quicksort, Heapsort, etc., that can solve this problem in O(n. log(n)) time, but those will not take advantage of the fact that there are many duplicated values in the array. A better approach is to use a counting sort.

How do you sort an array of objects based on another array?

If you use the native array sort function, you can pass in a custom comparator to be used when sorting the array. The comparator should return a negative number if the first value is less than the second, zero if they're equal, and a positive number if the first value is greater.


2 Answers

  1. Sort your array
  2. Swap elements at small even indexes with their higher antipodal counterparts:

    for ( i=0; i < arr.length/2; i+=2 )
        arr.swap(i,arr.length-1-i);
    

Edit: Okay, we should redefine the antipodal counterparts. Maybe this one is better: mixing the first and third quartile (denoted x, y in illustration), and mixing the second and third quartile (denoted u, v, w). Let the counterparts ascend parallel.

        25%  50%  75%
         |    |    |
    -----[----[----[----
    11122334455667788999
     x y u v w x y u v w  <-- u, v, w, x, y indicate swap positions
    16172839495161738495
like image 123
wnrph Avatar answered Oct 13 '22 00:10

wnrph


Hmm. Bubblesort comes to mind, but with a three-element comparison; that is, if item[x] and item[x + 1] are the same and item[x + 2] is different, swap item[x + 1] and item[x + 2]. Repeat iterating through the list until no swaps occur. Execution order is, of course, horrible, but that should meet your needs.

like image 24
Paul Sonier Avatar answered Oct 13 '22 00:10

Paul Sonier