Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calculate number of true (or false) elements in a bool array?

Tags:

arrays

c#

boolean

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?

like image 703
Evgeny Avatar asked Jul 30 '12 23:07

Evgeny


People also ask

Is 1 true or false in bool?

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.

How do you count boolean values in Java?

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.

Is 0 true or false in bool?

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.


2 Answers

return testArray.Count(c => c) 
like image 187
SLaks Avatar answered Oct 01 '22 07:10

SLaks


Use LINQ. You can do testArray.Where(c => c).Count(); for true count or use testArray.Where(c => !c).Count(); for false check

like image 39
Chris Knight Avatar answered Oct 01 '22 05:10

Chris Knight