Skip to content

Instantly share code, notes, and snippets.

@HashirHussain
Last active January 3, 2024 16:42
Show Gist options
  • Save HashirHussain/c155a0b51193c11d5e54ce239af6fb66 to your computer and use it in GitHub Desktop.
Save HashirHussain/c155a0b51193c11d5e54ce239af6fb66 to your computer and use it in GitHub Desktop.
Write an algorithm that takes an array and moves all of the zeros to the end, preserving the order of the other elements.
/**
Write an algorithm that takes an array and moves all of the zeros to the end, preserving the order of the other elements.
e.g.
moveZeros([false,1,0,1,2,0,1,3,"a"]) // returns[false,1,1,2,1,3,"a",0,0]
**/
function moveZeros(arr) {
//code me
}
/**
Test cases
assert.deepEqual(moveZeros([1,2,0,1,0,1,0,3,0,1]), [1, 2, 1, 1, 3, 1, 0, 0, 0, 0]);
assert.deepEqual(moveZeros([false,1,0,1,2,0,1,3,"a"]), [false,1,1,2,1,3,"a",0,0]);
assert.deepEqual(moveZeros([4,1,1,2,1,3,"a"]), [4,1,1,2,1,3,"a"]);
assert.deepEqual(moveZeros([1,0,0,1,0,1,0,3,0,1]), [1, 1, 1, 3, 1, 0, 0, 0, 0, 0]);
assert.deepEqual(moveZeros([0]), [0]);
assert.deepEqual(moveZeros([]), []);
**/
@HashirHussain
Copy link
Author

// Long way
function moveZeros(arr) {
  const result = arr;

  for (let i = 0; i < arr.length; i++) {
    shift();
  }

  function shift() {
    for (let i = 0; i < arr.length; i++) {
      if (result[i] === 0) {
        result.splice(i, 1);
        result.push(0);
        break;
      }
    }
  }
  return result;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment