简化条件布尔表达式 [英] Simplify if condition boolean expression

查看:907
本文介绍了简化条件布尔表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码中有 if-condition

if (a||a&&!b){
// do some stuff
}

我的 junit测试中的初始值

boolean a=true, b = true;

我后来认识到该声明可以简化为:

as I recognized later the statement can be simplified to:

if (a&&b)

变为绿色: Assert.assertTrue(a || a&&!b == a&& b);

我现在的问题是。有没有方法,工具,函数,图书馆等来检查布尔表达式是否有简化?

my question is now. Are there any methods, tools, functions, librarys etc. to check a boolean expression if there are simplifications?

谢谢你的帮助?

推荐答案

a || a && !b 

不等于

a && b

它等于 a

我想在你的JUnit测试中你使用了 a b 结果匹配的地方,但这并不意味着表达式是等价的—事实上它们不是。一个快速说服自己的方法是检查组合

I suppose that in your JUnit test you used a specific combination of values for a and b where the results match, but that does not mean that the expressions are equivalent—and in fact they aren't. A quick way to convince yourself of that is checking the combination

a = true, b = false;

您的原始表达清楚地为所有人提供 true a == true 的情况,但每当 b ==时,你的第二个表达式将产生 false false

Your original expression clearly yields true for all cases where a == true, but your second expression will yield false whenever b == false.

至于与 a 等效的正式证明,请参加扩张

As for a formal proof of equivalence to just a, take the expansion

a == a && (b || !b)
  == a && b || a && !b

插入原始表达式:

a || a && !b == a && b || a && !b || a && !b
             == a && b || a && !b
             == a

这篇关于简化条件布尔表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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