验证真值表的最小检查次数

Woo*_*Moo 1 java logic truthtable


我有一个java程序,我想验证3个布尔值中的任何一个是否为假.我想找出我能写的最小的表达式来检查排列.

if(!(needsWork && (needsApproval || isAdmin) ))

我认为这足以确保如果3个布尔值中的任何一个是假的,我想停止处理.但是,我有一种潜在的怀疑,我错过了一些东西.

Phi*_*unt 7

if (!needsWork || !needsApproval || !isAdmin)不行?Java支持短路评估.

  • 很公平.在那种情况下,`if(!(needsWork && needsApproval && isAdmin))`可能就像你能做到的那样简洁. (2认同)

Ber*_*t F 6

以来

`any 3 booleans are false` (i.e. `!a || !b || !c`)
Run Code Online (Sandbox Code Playgroud)

`(! (needsWork && (needsApproval || isAdmin))` (i.e. (! (a && ( b || c))`
Run Code Online (Sandbox Code Playgroud)

有不同的真值表,你确定不同的情况无关紧要吗?

a b c   (!a || !b || !c)    (! (a && (b || c)))
T T T          F                    F          
T T F          T                    F
T F T          T                    F
T F F          T                    T
F T T          T                    T
F T F          T                    T
F F T          T                    T
F F F          T                    T
Run Code Online (Sandbox Code Playgroud)

转换

我会经常使用布尔表达式来尝试澄清或简化它们,我使用这些逻辑转换来帮助我:

// You can push (distribute) `!` into parenthesis if you reverse the `||` or `&&` operator inside:
! (a || b)             <=> (! a && ! b)
! (a || b || c || ...) <=> (! a && ! b && ! c && ...)

! (a && b)             <=> (! a || ! b)
! (a && b && c && ...) <=> (! a || ! b || ! c || ...)

// You can drop parens when the boolean operator outside the parens is the same as inside:
(a || (b || c || ...)) <=> (a || b || c)
(a && (b && c && ...)) <=> (a && b && c)

// You can push (distribute) a boolean op into parenthesis by applying it to each term inside:
(a || (b && c)         <=> ((a || b) && (a || c)
(a || (b && c && ...)  <=> ((a || b) && (a || c) && (a || ...) ...

(a && (b || c)         <=> ((a && b) || (a && c))
(a && (b || c || ...)  <=> ((a && b) || (a && c) || (a || ...) ...

// XOR means the term values have to be different:
(a ^ b)                <=> ((a && !b) || (!a && b))

// XOR means the same as OR unless both terms are true:
(a ^ b)                <=> ((a || b) && ! (a && b))
Run Code Online (Sandbox Code Playgroud)

当然还有很多其他的,但这些是我经常使用的.它可能看起来很复杂,但是一旦你开始练习它们就很容易被人们所了解.

在您的情况下,如果您想查看一些可能的等效语句:

(! (needsWork && (needsApproval || isAdmin) ))
Run Code Online (Sandbox Code Playgroud)

这里有一些转变:

(! (needsWork && (needsApproval || isAdmin) ))   => [push the '!' through the `()`]
(! needsWork || ! (needsApproval || isAdmin) )   => [push the 2nd '!' through the `()`]
(! needsWork || (! needsApproval && ! isAdmin))
Run Code Online (Sandbox Code Playgroud)

但我没有看到你所拥有的任何真正的简化.

当然,如果检查没问题any of 3 booleans are false,那么您的选择很简单

(! needsWork || ! needsApproval || ! isAdmin) => [or pull the `!` outside the `()`]
(! (needsWork  && needsApproval && isAdmin))
Run Code Online (Sandbox Code Playgroud)

  • 这些被称为de Morgan的法律. (2认同)