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

后端 未结 8 1963
暗喜
暗喜 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

提交回复
热议问题