I have a set of five boolean values. If more than one of these are true I want to excecute a particular function. What is the most elegant way you can think of that would al
It's time for the obligatory LINQ answer, which in this case is actually quite neat.
var bools = new[] { true, true, false, false, false };
return bools.Count(b => b == true) > 1;
if you mean more than or equal to one boolean equals to true, you could do it like
if (bool1 || bool2 || bool3 || bool4 || bool5)
If you need more than one (2 and above) booleans equal to true, you can try
int counter = 0;
if (bool1) counter++;
if (bool2) counter++;
if (bool3) counter++;
if (bool4) counter++;
if (bool5) counter++;
if (counter >= 2) //More than 1 boolean is true
You mentioned
One interesting option is to store the booleans in a byte, do a right shift and compare with the original byte. Something like
if (myByte && (myByte >> 1))
I don't think that expression will give you the result you want (at least using C semantics, since the expression is not valid C#):
If (myByte == 0x08)
, then the expression will return true even though there's only one bit set.
If you meant "if (myByte & (myByte >> 1))
" then if (myByte == 0x0a)
the expression will return false even though there are 2 bits set.
But here are some techniques for counting the number of bits in a word:
Bit Twiddling Hacks - Counting bits
A variation you might consider is to use Kernighan's counting method, but bail out early since you only need to know if there's more than one bit set:
int moreThanOneBitSet( unsigned int v)
{
unsigned int c; // c accumulates the total bits set in v
for (c = 0; v && (c <= 1); c++)
{
v &= v - 1; // clear the least significant bit set
}
return (c > 1);
}
Of course, using a lookup table's not a bad option either.
I'd write a function to receive any number of boolean values. It would return the number of those values that are true. Check the result for the number of values you need to be positive to do something.
Work harder to make it clear, not clever!
private int CountTrues( params bool[] booleans )
{
int result = 0;
foreach ( bool b in booleans )
{
if ( b ) result++;
}
return result;
}
Shorter and uglier than Vilx-s version:
if (((a||b||c)&&(d||e))||((a||d)&&(b||c||e))||(b&&c)) {}
I would just cast them to ints and sum.
Unless you're in a super tight inner loop, that has the benefit of being easy to understand.