#include <stdio.h>
#include <stdbool.h>
#include <stddef.h>
/*
one_of: Check whether EXACTLY ONE element in an array satisfies a predicate.
Parameters:
arr - pointer to the first element of the array
n - number of elements
pred - pointer to a predicate function taking an int and returning bool
Returns:
true - if exactly one element satisfies pred
false - otherwise
Idiomatic C approach:
- Use a simple loop (fast and predictable).
- Count how many elements satisfy the predicate.
- Stop early if count exceeds 1 (efficient).
*/
bool one_of(const int *arr, size_t n, bool (*pred)(int)) {
size_t count = 0;
for (size_t i = 0; i < n; ++i) {
if (pred(arr[i])) {
if (++count > 1) {
return false; // Early exit: more than one match
}
}
}
return count == 1; // True only if exactly one match
}
/*
Predicate:
Check if a number is even.
*/
bool is_even(int x) {
return (x % 2) == 0;
}
/*
Predicate:
Check if a number is negative.
*/
bool is_negative(int x) {
return x < 0;
}
int main(void) {
int data1[] = { 3, 5, 7, 8 }; // exactly one even
int data2[] = { 2, 4, 6, 8 }; // four evens
int data3[] = { 1, -2, 3, 4 }; // exactly one negative
size_t size1 = sizeof(data1) / sizeof(data1[0]);
size_t size2 = sizeof(data2) / sizeof(data2[0]);
size_t size3 = sizeof(data3) / sizeof(data3[0]);
printf("Exactly one even in data1? %s\n",
one_of(data1, size1, is_even) ? "true" : "false");
printf("Exactly one even in data2? %s\n",
one_of(data2, size2, is_even) ? "true" : "false");
printf("Exactly one negative in data3? %s\n",
one_of(data3, size3, is_negative) ? "true" : "false");
return 0;
}
/*
run:
Exactly one even in data1? true
Exactly one even in data2? false
Exactly one negative in data3? true
*/