寻找 3 个布尔变量组合的更好方法

Better way of finding combination for 3 boolean variables

我有 3 个布尔变量 x、y、z。现在,在任何给定时刻,我都可以得到 2^3=8 种组合中的一种,如下所示。

例如x=true、y=false 和 z=false 或 x=false, y=true 和 z=true 等等。

如果我从编程的角度来看有 8 种情况,或者可能是 8 种或更多 if else 语句来确定当时的组合。 在任何给定时刻,如果我想知道存在什么组合(给定 x、y、z 的值),我怎么知道不使用 if-else 梯形图,这使得代码逻辑有点笨重。有没有better/simplelogic/way做的

如果你必须分别处理8种情况。您可以在变量中编码 x、y、z 的值,然后对该变量执行 switch case。下面的伪代码 -

v = 0
if (x) { v += 4 }
if (y) { v += 2 }
if (z) { v += 1 }

switch (v)
{
  case 0 : // all false
  case 1 : // z is true
  case 2 : // y is true
  case 3 : // z and y are true
  case 4 : // x is true
  ...
}

可能值得使用按位运算符而不是数值来确定哪些布尔变量打开或关闭。

// Assign the bitwise value of each variable
X = 4
Y = 2
Z = 1

// Setting X and Z as true using the bitwise OR operator.
v = X | Z // v = 4 + 1 = 5

// Checking if any of the variables are true using the bitwise OR operator
if (v | X+Y+Z) // v = 4 + 2 + 1 = 7

// Checking if ALL of the variables are true using the bitwise AND operator
if (v & X+Y+Z)

// Checking if variable Y is true using the bitwise OR operator
if (v | Y)

// Checking if variable Y is false using the bitwise OR operator
if (v | Y == false)

// Checking if ONLY variable Y is true using the bitwise AND operator
if (v & Y)

// Checking if ONLY variable Y is false using the bitwise AND operator
if (v & Y == false)

这样可以避免弄乱 X、Y、Z 值组合的结果数。它也更具可读性。