我有一个黑匣子处理系统,它接受布尔表达式,但不支持括号。我想输入这样的布尔表达式:
A && (B || C)但是,当我将其输入为:
A && B || C它对表达式进行评估,就好像我输入了:
(A && B) || C有没有任何方法可以重写我的表达式,以得到A && (B &(B\ C)的期望行为而不带括号?谢谢!
发布于 2018-01-30 19:46:51
优先级之间有一种关系,但是,您可以使用关联和分配律来解决这一问题。
A && B || A && C真值表匹配。
在实现这一点时要小心。并非所有编译器和语言都使用相同的优先级和计算顺序。
发布于 2018-01-30 19:37:52
编辑:没有左-右优先,对不起.
使用分配律和&&的优先级来检查A和B是否都是真,或者A和C都是真。
解决方案
A && B || A && C
分配律
x ^ (y v z) = (x ^ y) v (x ^ z)
x && (y || z) = (x && y) || (x && z)
function original(A, B, C) {
return A && (B || C);
}
function mySolution(A, B, C) {
return A && B || C && A;
}
console.log(original(true, true, true) == mySolution(true, true, true));
console.log(original(true, true, false) == mySolution(true, true, false));
console.log(original(true, false, true) == mySolution(true, false, true));
console.log(original(true, false, false) == mySolution(true, false, false));
console.log(original(false, true, true) == mySolution(false, true, true));
console.log(original(false, true, false) == mySolution(false, true, false));
console.log(original(false, false, true) == mySolution(false, false, true));
console.log(original(false, false, false) == mySolution(false, false, false));
https://stackoverflow.com/questions/48529167
复制相似问题