Fastest way to find correct combination with set o

2019-05-17 20:48发布

问题:

I have a set of booleans:x1, y1, z1, x2, z2, x3, y3, z3 each one is either true or false. Rather than writing dozens of if statements to check for the right true/false combo, what is the absolutely most efficient and fastest way to discover the correct combination of what is true and false?:

if(x1 == true && y1 == true && z1 == true && 
   x2 == true && z2 == true && 
   x3 == true && y3 == true && z3 == true)
  {
    //do stuff if this is correct combination
  }
else if(x1 == false && y1 == true && z1 == true && 
   x2 == true && z2 == true && 
   x3 == true && y3 == true && z3 == true)
  {
    //do stuff if this is correct combination
  }
 //do on and so forth for the next few dozen lines to check combo's

I was thinking of looping through with a for loop as well but this also seems very slow. This is going to be run dozens of times every second so I'm trying to make it as efficient as possible.

edit for clarification: y2 is purposely removed.

The reason I'm doing this is because I have a grid as follows:

x1, y1 ,z1
x2, y2 ,z2
x3, y3 ,z3

I'm trying to find if all the booleans around y2 are set to true or false because the texture applied to y2 will be different in each situation. For example, if x1, y1, and z1 are false but the rest true, y2 texture will be set to a specific image. If x3, z1, and x2 are false, and the rest true, then again y2 will be set to a different image. I'm trying to find what items around y2 are on or off so I can set the correct texture for y2.

回答1:

just convert it to a digit

x1 = 2^0 = 1
x2 = 2^1 = 2
x3 = 2^2 = 4
x4 = 2^3 = 8

you can do it for example like this:

int digit =
    (x1 ? 1 << 0 : 0) | (y1 ? 1 << 1 : 0) | (z1 ? 1 << 2 : 0) |
    (x2 ? 1 << 3 : 0) | (y2 ? 1 << 4 : 0) | (z2 ? 1 << 5 : 0) |
    (x3 ? 1 << 6 : 0) | (y3 ? 1 << 7 : 0) | (z3 ? 1 << 8 : 0);

or by using BitArray:

BitArray bits = new BitArray(new[] {x1, y1, z1, x2, y2, z2, x3, y3, z3});
int[] array = new int[1];
bits.CopyTo(array, 0);
int digit = array[0];

this way your combination of: false, true, true, true, true will be 01111 which is 15 decimal

you can then store your correct combination as a another digit and simply check if they are equal