Algorithm 12 - Counting sheep...

Beast from the east·2021년 10월 6일
0

Algorithm

목록 보기
12/27

Q.

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

A.

#include <stdbool.h>
#include <stddef.h>

size_t count_sheep(const bool *sheep, size_t count)
{
  size_t find = 0;
  while (count--)
  {
    if (sheep[count])
      find++;
  }
  return find;
}

another solution
size_t count_sheep(const bool *sheep, size_t count) {
  int n=0;
  while(count--) n += sheep[count];
  return n;
} -> true는 1, false는 0이기 때문에 가능한 식.
profile
Hello, Rabbit

0개의 댓글