#include <stdio.h>
#include <stdbool.h>
#include <stddef.h>
/*
one_of_equal: Check whether EXACTLY ONE element in an array
is equal to a specific value.
Parameters:
arr - pointer to the first element of the array
n - number of elements
value - the value to compare against
Returns:
true - if exactly one element equals 'value'
false - otherwise
Idiomatic C approach:
- Use a simple loop (fast and predictable).
- Count matches.
- Stop early if count exceeds 1 (efficient).
*/
bool one_of_equal(const int *arr, size_t n, int value) {
size_t count = 0;
for (size_t i = 0; i < n; ++i) {
if (arr[i] == value) {
if (++count > 1) {
return false; // Early exit: more than one match
}
}
}
return count == 1; // True only if exactly one match
}
int main(void) {
int data1[] = { 5, 3, 8, 1 }; // exactly one 3
int data2[] = { 7, 7, 7, 7 }; // four 7s
int data3[] = { 2, 4, 6, 8 }; // zero 5s
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 equal to 3 in data1? %s\n",
one_of_equal(data1, size1, 3) ? "true" : "false");
printf("Exactly one equal to 7 in data2? %s\n",
one_of_equal(data2, size2, 7) ? "true" : "false");
printf("Exactly one equal to 5 in data3? %s\n",
one_of_equal(data3, size3, 5) ? "true" : "false");
return 0;
}
/*
run:
Exactly one equal to 3 in data1? true
Exactly one equal to 7 in data2? false
Exactly one equal to 5 in data3? false
*/