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

[Codewars] Counting sheep... (8 kyu) / JavaScript

by fluss 2022. 12. 3.

https://www.codewars.com/kata/54edbc7200b811e956000556

 

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:

Consider an array/list of sheep where some sheep may be missing from their place. We need a function that counts the number of sheep present in the array (true means present).

For example,

[true,  true,  true,  false,
  true,  true,  true,  true ,
  true,  false, true,  false,
  true,  false, false, true ,
  true,  true,  true,  true ,
  false, false, true,  true]

The correct answer would be 17.

Hint: Don't forget to check for bad values like null/undefined

 

설명:

일부 양이 그들의 자리에서 빠진 양의 배열/리스트 고려해보세요. 존재하는 양의 수를 세는 함수가 필요합니다(true는 존재한다는 것을 의미합니다).

예를 들어,

[true,  true,  true,  false,
  true,  true,  true,  true ,
  true,  false, true,  false,
  true,  false, false, true ,
  true,  true,  true,  true ,
  false, false, true,  true]

 

정답은 17이 될 것입니다.

힌트 : null/undefined와 같은 잘못된 값을 체크하는 것을 잊지 마세요.

 
 

풀이

반복문으로 배열의 요소를 하나씩 체크해 ture일 경우를 세어 반환해주었다.

 

코드

function countSheeps(arrayOfSheep) {
  let count = 0;
  for(let i = 0; i < arrayOfSheep.length; i++){
    if(arrayOfSheep[i]) count += 1
  }
  return count;
}

 

다른 사람의 좋았던 풀이

function countSheeps(arrayOfSheeps) {
  return arrayOfSheeps.filter(Boolean).length;
}

filter를 이용하여 true인 경우만 걸러낸 배열을 만들고 그 길이를 반환하였다.

댓글