最快的方式找到一组8布尔值的正确组合 [英] Fastest way to find correct combination with set of 8 booleans

查看:168
本文介绍了最快的方式找到一组8布尔值的正确组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组布尔值: X1,Y1,Z1,X2,Z2,X3,Y3,Z3 每一个都是真或假。而不是写几十个if语句来检查为右真/假的组合,什么是发现了什么是真与假的正确组合绝对最有效和最快捷的方式:

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

我想用一个循环,通过for循环,但这似乎也很慢。这是将要运行数十次每一秒,所以我试图使它尽可能高效。

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.

澄清编辑:Y2被故意删除

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

我试图找到,如果Y2周围所有的布尔值设置为true或false,因为用于Y2纹理将在每一种情况不同。例如,如果X1,Y1,和Z1都是假的,但其余的真,Y2纹理将被设置为一个特定的图象。如果X3,Z1,和x2是假,其余真,则再次Y2将被设置为一个不同的图像。我试图找出是打开还是关闭,所以我可以设置正确的纹理Y2什么Y2左右的项目。

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.

推荐答案

只是把它转换成一个数字

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);

或使用 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];

这样,您的组合:假的,真的,真的,真的,真的将01111这是 15 小数

您可以那么你的正确组合存储为另一个数字,只是检查,如果他们是平等的。

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

这篇关于最快的方式找到一组8布尔值的正确组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆