본문 바로가기

Java Script/알고리즘 풀이

[알고리즘] 0825

문제 - Codewars_Counting Sheep (8kyu)

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/undefine

문제 풀이

function countSheeps(arrayOfSheep) {
  let count = 0;
  for(let i = 0; i < arrayOfSheep.length; i++){
    if(arrayOfSheep[i] === true)
      count++;
      }
  return count;
}
  1. for 구문을 사용해서 arrayOfSheep 배열 내의 값이 true와 동일할 시 변수로 선언된 "count"의 값을 더하라는 코드 작성

코드 비교

function countSheeps(arrayOfSheeps) {
  return arrayOfSheeps.filter(Boolean).length;
}
  1. filter 함수 내 callback 함수는 truethy 값을 반환하기 때문에 filter에 Boolean을 넣어서 true 값에 대한 갯수를 반환하게 작성한 코드 굿

추가 학습 필요한 부분

  1. forEach 구문과 filter

'Java Script > 알고리즘 풀이' 카테고리의 다른 글

[알고리즘] 0827  (0) 2023.08.27
[알고리즘] 0826  (0) 2023.08.26
[알고리즘] 0824  (0) 2023.08.24
[알고리즘] 0823  (0) 2023.08.23
[알고리즘] 0822  (0) 2023.08.22