【问题标题】:Boolean Expression Optimization For All AND Conditions所有 AND 条件的布尔表达式优化
【发布时间】:2015-02-14 19:51:08
【问题描述】:

我正在尝试解决一个简单规则引擎的布尔表达式优化问题。

这是我想要做的,假设我有以下 5 个条件(其中 a、b、c、d、e、f 是复杂的布尔表达式)

if (a AND b AND c AND d AND e AND f) then do-1 
if (a AND b AND c AND d AND e) then do-2 
if (a AND b AND c AND d) then do-3
if (a AND b AND c) then do-4
if (a AND b) then do-5

如果我以线性顺序执行这些条件,我会

- evaluate "a" for 5 times
- evaluate "b" for 5 times
- evaluate "c" for 4 times
- evaluate "d" for 3 times
- evaluate "e" for 2 times
- evaluate "f" for 1 time

我想从中创建一个表达式执行树,以便每个表达式 (a,b,c,d,e,f) 的评估次数最少。 完美的解决方案是每个表达式只计算一次。我认为这可以通过创建树来实现,其中所有这些条件都是树的一部分。

树可能看起来像这样

if(a AND b) then do-5  {
    if(c) then do-4 {
        if(d) then do-3 {
            if(e) then do-2 {
                if(f) then do-1 
            }
        }
    }       
}

我的问题是 -我怎样才能从上面列出的布尔表达式集中生成这棵树?

相关问题:

Algorithm for evaluating nested logical expression

Converting an expression to conjunctive normal form with a twist

Is it useful in C# to apply DeMorgan's theorem to manually optimize boolean expressions in conditional statements (e.g. if conditions)

【问题讨论】:

  • 问题是什么?
  • @tmr232 - 感谢您的回复。对不起,我在不同的时区,所以回复晚了。我已经更新了问题。
  • 如果你上面的五个if 语句是源代码(而不是来自数据库或其他东西),似乎你可以只做bool atemp = a; bool btemp = b;,等等,然后就请参阅if 语句中的那些临时工。
  • 这更像是一个 switch-case 而不是一棵树。我假设你有一个所有布尔值的列表。如果是这样,我会使用list_of_bools.index(False) 来获取正确的大小写,然后使用函数表跳转到正确的代码。
  • 感谢您的回复。抱歉,我似乎无法清楚地描述我的问题。让我想一个更好的方式来描述。

标签: boolean logical-operators boolean-expression tree-traversal boolean-operations


【解决方案1】:

你可以这样处理:

var booleans = [a, b, c, d, e, f];
var i = 0;
while(booleans[i]) i++;

switch(i) {
    case 0:
        // do something
        break;
    case 1:
        // do something
        break;
    ...
}

我很确定有一种方法可以将 while 循环与 switch 运算符合并,从而得到更优化的东西。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-23
    • 1970-01-01
    • 2016-07-13
    • 2016-02-20
    • 1970-01-01
    相关资源
    最近更新 更多