Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If statement for multiple scenarios

Tags:

c#

I am struggling completing this if statement. There must be an easier way to go through all combination because this can't be good practice.

if( one == true && two == true && three == true ...)
else if( one != true && two == true && three == true ...)

I wonder if I want to go through all combinations is there any other way of doing this rather than duplicating the expression?

like image 742
MohammedT Avatar asked Nov 28 '22 01:11

MohammedT


1 Answers

One way would be converting your one, two, and three values to a single int with the bits properly set, and using a switch statement on binary masks, like this:

int combined=0;
// Construct a binary representation using your Boolean values as bits:
// Value of one goes to bit zero
if (one) combined   |= (1 << 0);
// Value of one goes to bit one
if (two) combined   |= (1 << 1);
// Value of three goes to bit two
if (three) combined |= (1 << 2);
switch (combined) {
case 0: // All false
    break;
case 1: // one is true, other are all false
    break;
...
case 7: // All true
    break;
}

All eight combinations are now encoded as integer values:

int    three two one
_--    ----- --- ---
0    -    0   0   0 
1    -    0   0   1 
2    -    0   1   0 
3    -    0   1   1 
4    -    1   0   0 
5    -    1   0   1 
6    -    1   1   0 
7    -    1   1   1 

It goes without saying that you need to heavily comment code like this for readers of your code who have not memorized binary representations of small numbers.

like image 180
Sergey Kalinichenko Avatar answered Dec 18 '22 07:12

Sergey Kalinichenko