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 arrayL
($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 = 0;
for (int i = 0; i < count; ++i) sum += arr[i];
return (sum>0)? 1 : 0;
}
Option 2:
#include <stddef.h>
int invite_more_women(int *arr, size_t count) {
int balance = 0;
while (count--)
balance += *arr++;
return balance > 0;
}
Option 3:
#include <stdbool.h>
#include <stddef.h>
bool invite_more_women(const int attendee_genders[], size_t count) {
ptrdiff_t sum = 0;
for (size_t i = 0; i < count; i++)
sum += attendee_genders[i];
return sum > 0;
}
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(0, NULL, false);
}