计算条件语句的技术或模式

计算科学 算法
2021-12-04 07:46:19

我正在尝试创建一个比较四 (4) 个真/假条件的条件语句。根据这四个条件的状态(真或假),条件语句将通过或失败。我有一张表格,告诉我所有可能排列的结果(通过/失败)。2^4 = 16 种可能的排列。

+-------------+-------+-------+-------+-------+-------+-------+-------+-------+------+-------+-------+-------+-------+-------+-------+-------+
|             |  Pass |  Pass |  Pass |  Pass |  Pass |  Pass |  Pass |  Pass | Fail |  Fail |  Fail |  Fail |  Fail |  Fail |  Fail |  Fail |
+-------------+-------+-------+-------+-------+-------+-------+-------+-------+------+-------+-------+-------+-------+-------+-------+-------+
| Condition A |  True |  True | False | False | False |  True |  True | False | True | False |  True |  True |  True | False | False | False |
+-------------+-------+-------+-------+-------+-------+-------+-------+-------+------+-------+-------+-------+-------+-------+-------+-------+
| Condition B |  True |  True | False | False |  True | False | False |  True | True |  True | False | False |  True | False |  True | False |
+-------------+-------+-------+-------+-------+-------+-------+-------+-------+------+-------+-------+-------+-------+-------+-------+-------+
| Condition C | False |  True |  True | False |  True |  True | False | False | True |  True |  True | False | False |  True | False | False |
+-------------+-------+-------+-------+-------+-------+-------+-------+-------+------+-------+-------+-------+-------+-------+-------+-------+
| Condition D | False | False |  True |  True | False | False | False |  True | True |  True |  True |  True |  True | False | False | False |
+-------------+-------+-------+-------+-------+-------+-------+-------+-------+------+-------+-------+-------+-------+-------+-------+-------+

是否有一种模式/技术可以用来将此矩阵转换为条件语句,例如以下...

if (A == True && (B == True || C == False || D == True))
{
  // Pass code here
}
else
{
  // Fail code here
}

只是为了澄清,这是我(A == True && (B == True || C == False || D == True))在上面的例子中试图计算的条件语句。将来我可能会有或多或少的排列,我正在尝试确定一种模式/技术,而不是尝试或错误来生成条件语句。

2个回答

一种方法是使用条件的直接二进制表示。这意味着,例如,前两列可以表示为:

(A 真, B 真, C 假, D 假) --> (1100)
(A 真, B 真, C 真, D 假) --> (1110)
...

然后,您可以将列表示的条件定义为位集:

                                          //[A,B,C,D]
std::bitset<4> column_one_condition(12); // [1,1,0,0]
std::bitset<4> column_two_condition(14); // [1,1,1,0]
...

完成后,您获得的输入可以通过 == 运算符与您的条件进行比较。

if(input_bitset ==column_one_condition) { pass();}
if(input_bitset ==column_two_condition) { pass();}
                ...                                 

这可能不是超级直观,但它应该是闪电般的快速并且在添加更多条件时也可以扩展。此外,每个条件需要一行。如果您执行完整的 if-then-else 语法,相同的逻辑将很快失控。

还应该可以使用矩阵(2D bool 数组)来表示您的表格并编写方法来评估您针对该矩阵的输入。这可能更紧凑,但可能不那么可读。

请注意,您发布的 if-then-else 变体可以通过使用否定“!”进一步缩短。如果条件的数量保持相对较低,您可以像这样执行单行:

if( A and  B and !C and !D) pass();
if( A and  B and  C and !D) pass();
if( A and  B and !C and !D) pass();
if(!A and !B and  C and  D) pass();
if(!A and !B and !C and  D) pass();
// ...
if( A and  B and  C and  D) fail();

正如您所说,您需要的行数呈指数增长,因此在某些时候这会得到非常多的样板代码。