简体   繁体   中英

Simplify if condition boolean expression

I have this if-condition in my code:

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

with that intial values from my junit test :

boolean a=true, b = true;

as I recognized later the statement can be simplified to:

if (a&&b)

becomes green: Assert.assertTrue(a||a&&!b == a&&b);

Are there any further simplifications? How could I have recognized that this boolean expression could be simplified?

Just check the truth table (I've added parentheses)

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

  a|b|result
  ----------
  T|T|T 
  T|F|T 
  F|T|F 
  F|F|F

As we can see, the formula doesn't depend on b , and can be simplified to only

  a

Finally

  if (a) {
    // do some stuff
  }

For formulae with many variables when truth table is too long for manual analysis you can use Karnaugh maps as Eomm proposed.

One common technique used to simplify complex Boolean expressions is Karnaugh Maps . It is relatively easy to learn, and it can help you produce shorter expressions, or even build Boolean expressions from a truth table.

Karnaugh Map for your expression is very simple - it looks like this:

在此处输入图片说明

It simplifies to a , not a && b .

You could use Karnaugh map for simplify boolean logic.

With 3 or more variables is the best way

a || a && !b 

is not equal to

a && b

It is equal to just a .

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;

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

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

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

Plugging into your original expression:

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

Wolfram Alpha actually does boolean algebra simplification. It might take a little converting the answer it gives you to make it compatible with your programming language, but the concept works and checks out fine. Here's a link to the page

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM