我有一套布尔值:x1, y1, z1, x2, z2, x3, y3, z3
每一个都是真或假。而不是写几十个if语句来检查正确的真/假组合,找到正确和错误的正确组合的绝对最有效和最快的方法是什么?:
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
我正在考虑使用for循环进行循环,但这似乎也很慢。这将每秒运行几十次,所以我试图让它尽可能高效。
编辑澄清:故意删除y2。
我这样做的原因是因为我有一个如下网格:
x1, y1 ,z1
x2, y2 ,z2
x3, y3 ,z3
我试图找出y2周围的所有布尔值是否都设置为true或false,因为应用于y2的纹理在每种情况下都会有所不同。例如,如果x1,y1和z1为假但其余为真,则y2纹理将设置为特定图像。如果x3,z1和x2为假,其余为真,那么y2将再次设置为不同的图像。我试图找到y2周围的项目是打开还是关闭所以我可以为y2设置正确的纹理。
答案 0 :(得分:6)
只需将其转换为数字
x1 = 2^0 = 1
x2 = 2^1 = 2
x3 = 2^2 = 4
x4 = 2^3 = 8
你可以这样做:
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);
或使用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];
这样你的组合:false,true,true,true,true将是01111,即15
十进制
然后,您可以将正确的组合存储为另一个数字,并检查它们是否相等