본문 바로가기
알고리즘/Codewars

[Codewars] Moving Zeros To The End (5 kyu) / JavaScript

by fluss 2022. 12. 31.

https://www.codewars.com/kata/52597aa56021e91c93000cb0

 

Codewars - Achieve mastery through coding practice and developer mentorship

A coding practice website for all programming levels – Join a community of over 3 million developers and improve your coding skills in over 55 programming languages!

www.codewars.com

 

DESCRIPTION:

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

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

설명:

배열을 받아 다른 요소의 순서를 유지하면서 모든 0을 끝으로 옮기는 알고리즘을 작성하세요.

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

 

풀이

배열에서 0의 개수를 세고 0이 아닌 경우 모두 다른 배열에 넣어준다. 그리고 0의 개수만큼 새로운 배열의 끝에 0을 넣어주었다.

 

코드

function moveZeros(arr) {
  let sortedArr = [];
  let count = 0;
  for(let i = 0; i < arr.length; i++){
    if(arr[i] === 0){
      count++;
    } else{
      sortedArr.push(arr[i]);
    }
  }
    
  for(let i = 0; i < count; i++){
    sortedArr.push(0);
  }
  return sortedArr;
}

댓글