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;
}
'알고리즘 > Codewars' 카테고리의 다른 글
[Codewars] Beginner - Lost Without a Map(8 kyu) / JavaScript (0) | 2023.01.03 |
---|---|
[Codewars] String ends with? (7 kyu) / JavaScript (1) | 2023.01.02 |
[Codewars] Is n divisible by x and y? (8 kyu) / JavaScript (0) | 2022.12.30 |
[Codewars] Keep Hydrated! (8 kyu) / JavaScript (0) | 2022.12.29 |
[Codewars] Ones and Zeros (7 kyu) / JavaScript (0) | 2022.12.28 |
댓글