Suppose I have an array filled with Boolean values and I want to know how many of the elements are true.
private bool[] testArray = new bool[10] { true, false, true, true, false, true, true, true, false, false }; int CalculateValues(bool val) { return ??? }
CalculateValues should return 6 if val is true, or 4 if val is false.
Obvious solution:
int CalculateValues(bool val) { int count = 0; for(int i = 0; i<testArray.Length;i++) { if(testArray[i] == val) count++; } return count; }
Is there an "elegant" solution?
Boolean Variables and Data Type ( or lack thereof in C ) C does not have boolean data types, and normally uses integers for boolean testing. Zero is used to represent false, and One is used to represent true. For interpretation, Zero is interpreted as false and anything non-zero is interpreted as true.
The countTrue() method of Booleans Class in Guava Library is used to count the number of values that are true in the specified boolean values passed as the parameter. Parameters: This method accepts the boolean values among which the true values are to be count.
Also, a numeric value of zero (integer or fractional), the null value ( None ), the empty string, and empty containers (lists, sets, etc.) are considered Boolean false; all other values are considered Boolean true by default.
return testArray.Count(c => c)
Use LINQ. You can do testArray.Where(c => c).Count();
for true count or use testArray.Where(c => !c).Count();
for false check
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With