Codewars Challenge Day 3: Moving Zeros To The End

qroia

Qroia FAK(C)E

Posted on July 14, 2022

Codewars Challenge Day 3: Moving Zeros To The End

Details

Name Kata: Moving Zeros To The End
5kuy
Description:
Write an algorithm that takes an array and moves all of the zeros to the end, preserving the order of the other elements.
Example

moveZeros([false,1,0,1,2,0,1,3,"a"]) // returns[false,1,1,2,1,3,"a",0,0]
Enter fullscreen mode Exit fullscreen mode

My Solutions

JavaScript

const moveZeros = (arr) => {
  if (arr[0]===0){arr.push(arr.splice(i, 1).pop())}
  for(var i=arr.length;i>0;i--){if(arr[i]===0){arr.push(arr.splice(i,1).pop())}}
  return arr
}
Enter fullscreen mode Exit fullscreen mode

Python

from typing import List

def move_zeros(lst: List) -> List:
    return [x for x in lst if x != 0] + [x for x in lst if x == 0]
Enter fullscreen mode Exit fullscreen mode

PHP

function moveZeros(array $items): array
{
    return array_pad(
      array_filter(
        $items, function($x) {return $x !== 0 and $x !== 0.0;}
      ), count($items), 
     0);
}
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
qroia
Qroia FAK(C)E

Posted on July 14, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related