简体   繁体   English

如何重新排序数组以避免连续重复

[英]How to reorder an Array to avoid consecutive duplicates

I have an array of numbers [1,2,2,2,3,4,5]我有一组数字 [1,2,2,2,3,4,5]

What I want to do is to sort the array to avoid equal numbers consecutively [1,2,3,2,4,2,5].我想要做的是对数组进行排序以避免连续相等的数字[1,2,3,2,4,2,5]。 but I don't want to delete any number from the array, in the worse case when the duplicated numbers are more than the other numbers I would like to put those that are impossible to merge in other arrays.但我不想从数组中删除任何数字,在更糟糕的情况下,当重复的数字多于其他数字时,我想将那些无法合并的数字放在其他 arrays 中。

const original = [1,2,2,2,2,2,2,3,4];
const merged = [];
const rest = [];

For example [1,2,2,2,2,2,2,3,4] the result expected should be [2,1,2,3,2,4,2] and another array with [2,2] in the original array I have 6 times 2 and I was able to merge 4 of the six in the rest例如 [1,2,2,2,2,2,2,3,4] 预期的结果应该是 [2,1,2,3,2,4,2] 和另一个数组 [2,2]在原始数组中,我有 6 次 2,我能够合并 rest 中的 6 个中的 4 个

    const original = [1,2,2,2,2,2,2,3,4];
    const merged = [2,1,2,3,2,4,2];
    const rest = [2,2];

I was trying to play with this algorithm but there is no way to get the respected result, this algorithm deletes the duplicates我试图玩这个算法,但没有办法得到尊重的结果,这个算法删除了重复项

const testArr = [1, 1, 2, 2, 3, 3, 1, 1, 1];
const compress = (arr, len = 0, canDelete = false) => {
   if(len < arr.length){
      if(canDelete){
         arr.splice(len, 1);
         len--;
      }
      return compress(arr, len+1, arr[len] === arr[len+1])
   };
   return;
};
compress(testArr);
console.log(testArr);

Any Idea on what is the best way to face this kind of problem?关于面对此类问题的最佳方法是什么的任何想法?

It was a very interesting one, here is my solution:这是一个非常有趣的问题,这是我的解决方案:


const original = [1,2,2,2,2,3,3,2,2,2,3,4]
console.log("Before: ", original)

let object_keys = {}

//Step 1: map all the values and how many times it duplicated
for(let val of original){
  if(object_keys[val]){
    object_keys[val]++
  }else{
    object_keys[val] = 1
  }
}

console.log(object_keys) // { '1': 1, '2': 7, '3': 3, '4': 1 }

//Step 2: Run over the object and create a new array. the method is each iterate, append new key

const get_the_most_duplicated_val = (object_keys, except) => {
  let max = 0
  let key = ''
  for(let v in object_keys){
    if(object_keys[v] > max && !except.includes(v)){
      max = object_keys[v]
      key = v
    }
  }
  return key
}

let merged = []
let rest = []

let merged_is_completed = false
while(!merged_is_completed){

  const append_val = (key) => {
    merged.push(key)
    object_keys[key]--
    if(object_keys[key] == 0){
      delete object_keys[key]
    }
  }

  const last_val = () => {
    return merged[merged.length - 1]
  }

  let most_key = get_the_most_duplicated_val(object_keys, [])
  append_val(most_key)
  let most_key2 = get_the_most_duplicated_val(object_keys, [most_key])
  append_val(most_key2)

  if(Object.keys(object_keys).length == 1){
    if(last_val() != Object.keys(object_keys)[0]){
      append_val(Object.keys(object_keys)[0])
    }
    for(let i=0;i<object_keys[Object.keys(object_keys)[0]];i++){
      rest.push(Object.keys(object_keys)[0])
    }
    merged_is_completed = true
  }
}
console.log("Merged: ", merged)
console.log("Rest: ", rest)

I put it in Codepen so you can test it by yourself:) https://codepen.io/gofmannir/pen/vYXEmPa?editors=0011我把它放在 Codepen 中,你可以自己测试:) https://codepen.io/gofmannir/pen/vYXEmPa?editors=0011

Was an interesting Task, I just wrote a little code it doesn't work perfectly but you can improve it.是一个有趣的任务,我只是写了一个小代码,它不能完美地工作,但你可以改进它。

const insert = (el, result) => {
    if (el !== result.merged[result.merged.length - 1]) {
        result.merged.push(el);
        if (result.rest.length !== 0) {
            for (let i = 0; i < result.rest.length; i++) {
                let restItemToInsert = result.rest[i];
                if (result.merged[result.merged.length - 1] !== restItemToInsert) {
                    result.merged.push(restItemToInsert);
                    result.rest.splice(i, 1);
                }
            }
        }
    } else {
        result.rest.push(el);
    }
    return result;
}

const recursive = (arr) => {
    let el = arr.shift();
    return arr.length === 0 ? { rest: [], merged: [el]} : insert(el, recursive(arr));
}

const testArr = [1, 1, 2, 2, 3, 3, 1, 1, 1];
const testArr2 = [1, 1, 1, 1, 3, 3, 1, 1, 1];
const original = [1,2,2,2,2,2,2,3,4];
console.log(recursive(original));
console.log(recursive(testArr));
console.log(recursive(testArr2));

If you run the code, you should get something like this.如果你运行代码,你应该得到类似这样的东西。

{ rest: [ 2, 2, 2, 2 ], merged: [ 4, 3, 2, 1, 2 ] }
{ rest: [], merged: [
    1, 3, 1, 3, 1,
    2, 1, 2, 1
  ] }
{ rest: [ 1, 1, 1, 1 ], merged: [ 1, 3, 1, 3, 1 ] }

You can see, for your const original = [1,2,2,2,2,2,2,3,4];您可以看到,对于您的const original = [1,2,2,2,2,2,2,3,4]; it doesn't give the right answer.它没有给出正确的答案。 But you can improve it and make it work.但是你可以改进它并让它发挥作用。

UPDATE更新

I wrote a better insert function, this should work for any array from your example.我写了一个更好的插入 function,这应该适用于您示例中的任何数组。

const insert = (el, result) => {
    result.rest.unshift(el);
    for (let i = 0; i < result.rest.length; i++) {
        let restItem = result.rest[i];
        for (let j = 0; j < result.merged.length; j++) {
            let mergedItem = result.merged[j];
            if(mergedItem !== restItem) {
                if (result.merged[result.merged.length - 1] !== restItem) {
                    result.merged.push(restItem);
                    result.rest.splice(i, 1);
                    i = -1;
                    break;
                } 
                
                if(result.merged[0] !== restItem) {
                    result.merged.unshift(restItem);
                    result.rest.splice(i, 1);
                    i = -1;
                    break;
                }

                if (result.merged[j + 1] && result.merged[j + 1] !== restItem) {
                    result.merged.splice(j + 1, 0, restItem);
                    result.rest.splice(i, 1);
                    i = -1;
                    break;
                }            
            }
        }
    }
    return result;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM