Home > Software design >  Moving Zeros To The End. My solution does't satisfy
Moving Zeros To The End. My solution does't satisfy

Time:12-24

The task is -

Write an algorithm that takes an array and moves all of the zeros to the end, preserving the order of the other elements.

I've created the next function

const moveZeros = (arr) => {
  const finalArray = arr;
  finalArray.forEach((element, i) => {
    if (element === 0) {
      finalArray.splice(i, 1);
      finalArray.push(0);
    }
    if (finalArray[i - 1] === 0) {
      finalArray.splice(i - 1, 1);
      finalArray.push(0);
    }
  });
  return finalArray;
};

So, calling
moveZeros([false,1,0,1,2,0,1,3,"a"]) works good,
but calling moveZeros([9, 9, 1, 2, 1, 1, 3, 1, 9, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0])
also works but unsatisfactory, cause expected
[9, 9, 1, 2, 1, 1, 3, 1, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Arrays sort ok, I don't understand what's a problem?
Explain me please.

CodePudding user response:

Why not simply filter the zeros and concat them to the rest?

function moveZeros( arr ) {
  let zeros = arr.filter((n) => n === 0)
  let rest = arr.filter((n) => n !== 0)
  return rest.concat(zeros)
}

console.log(JSON.stringify(moveZeros([false,1,0,1,2,0,1,3,"a"])))
console.log(JSON.stringify(moveZeros([9, 9, 1, 2, 1, 1, 3, 1, 9,  0, 9,  0,  0,  0,  0,  0,  0,  0,  0,  0])))

CodePudding user response:

You can do that...

You will also have to reduce the number of iterations, by ignoring the last zeros, (which avoids deleting unnecessary swapping of zeros).

moveZeros([false,1,0,1,2,0,1,3,"a"]) 
moveZeros([9, 9, 1, 2, 1, 1, 3, 1, 9,  0, 9,  0,  0,  0,  0,  0,  0,  0,  0,  0])

function moveZeros( arr )
  {
  let pos = 0, posMax = arr.length
    ;
  for ( ; posMax > 0 && arr[posMax -1] === 0 ; posMax--)
    {} 
  while (pos < posMax)
    {
    if (arr[pos] === 0)
      {
      posMax--
      arr.splice(pos, 1)
      arr.push(0)
      }
    else pos  ;
    }
  console.log( JSON.stringify( arr ))
  }

  • Related