Skip to content

How to Invite More Women in C

The challenge

Task

King Arthur and his knights are having a New Years party. Last year Lancelot was jealous of Arthur, because Arthur had a date and Lancelot did not, and they started a duel.

To prevent this from happening again, Arthur wants to make sure that there are at least as many women as men at this year’s party. He gave you a list of integers of all the party goers.

Arthur needs you to return true if he needs to invite more women or false if he is all set.

Input/Output

  • [input] integer array L ($a in PHP)

An array (guaranteed non-associative in PHP) representing the genders of the attendees, where -1 represents women and 1 represents men.

2 <= L.length <= 50

  • [output] a boolean valuetrue if Arthur need to invite more women, false otherwise.

The solution in C

Option 1:

#include <stddef.h> int invite_more_women(int *arr, size_t count) { int sum = ; for (int i = ; i < count; ++i) sum += arr[i]; return (sum>)? 1 : ; }
Code language: C++ (cpp)

Option 2:

#include <stddef.h> int invite_more_women(int *arr, size_t count) { int balance = ; while (count--) balance += *arr++; return balance > ; }
Code language: C++ (cpp)

Option 3:

#include <stdbool.h> #include <stddef.h> bool invite_more_women(const int attendee_genders[], size_t count) { ptrdiff_t sum = ; for (size_t i = ; i < count; i++) sum += attendee_genders[i]; return sum > ; }
Code language: C++ (cpp)

Test cases to validate our solution

#include <stdbool.h> #include <stddef.h> #include <criterion/criterion.h> extern void do_test (size_t count, const int array[count], bool expected); #define ARR_LEN(array) (sizeof(array) / sizeof *(array)) #define sample_test(array, expected) do_test(ARR_LEN(array), array, expected) Test(tests_suite, sample_tests) { sample_test(((int[]){1, -1, 1}), true); sample_test(((int[]){-1, -1, -1}), false); sample_test(((int[]){1, -1}), false); sample_test(((int[]){1, 1, 1}), true); do_test(, NULL, false); }
Code language: C++ (cpp)

See also  How to Solve the Maze Runner in C
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x