countSheeps.js (8kyu 11)

Codewars 알고리즘 풀이


Description

  • We need a function that counts the number of sheep present in the array.
    • 배열에 있는 양의 수를 반환한다.



Solution 01

function countSheeps(arr) {
  let result = 0;
  
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === true) {
      result++;
    }
  }
  
  return result;
}

countSheeps([]);                          // 0
countSheeps([true, false, false, true]);  // 2
countSheeps(
  [
    true, true, true, false,
    true, true, true, true,
    true, false, true, false,
    true, false, false, true,
    true, true, true, true,
    false, false, false, true
  ]
);  // 16


Solution 02

function countSheeps(arr) {
  let result = 0;
  
  arr.forEach(sheep => {
    if (sheep) {
      result++;
    }
  });
  
  return result;
}

countSheeps([]);                          // 0
countSheeps([true, false, false, true]);  // 2
countSheeps(
  [
    true, true, true, false,
    true, true, true, true,
    true, false, true, false,
    true, false, false, true,
    true, true, true, true,
    false, false, false, true
  ]
);  // 16


Solution 03

function countSheeps(arr) {
  let result = 0;
  
  arr.map(sheep => {
    if (sheep) {
      result++;
    }
  });
  
  return result;
}

countSheeps([]);                          // 0
countSheeps([true, false, false, true]);  // 2
countSheeps(
  [
    true, true, true, false,
    true, true, true, true,
    true, false, true, false,
    true, false, false, true,
    true, true, true, true,
    false, false, false, true
  ]
);  // 16


Solution 04

function countSheeps(arr) {
  return arr.reduce((result, i) => result + (i === true ? 1 : 0), 0);
}

countSheeps([]);                          // 0
countSheeps([true, false, false, true]);  // 2
countSheeps(
  [
    true, true, true, false,
    true, true, true, true,
    true, false, true, false,
    true, false, false, true,
    true, true, true, true,
    false, false, false, true
  ]
);  // 16


Solution 05

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

countSheeps([]);                          // 0
countSheeps([true, false, false, true]);  // 2
countSheeps(
  [
    true, true, true, false,
    true, true, true, true,
    true, false, true, false,
    true, false, false, true,
    true, true, true, true,
    false, false, false, true
  ]
);  // 16