Solving logical expressions in Java with minimum iterations

Dixer :

I'm working on solving the logical expressions in Java comprising of AND, OR, and NOT operators.

The program has to output if the input was TRUE for any Boolean values of the variables included. I've done it successfully but it is not efficient enough.

My current solution goes like:

Make a truth table for each variable in the expression and evaluate row by row.

(p ∧ ¬q) ∨ (r ∧ s) ∨ (¬p ∨ u)

In the above example, I'll have to evaluate the whole expression with a truth table of variables p q r s.

Now, I'm thinking of implementing an alternate solution that goes like this: Consider the example above.

We can notice that even by just solving the p ∧ ¬q part, all of the expression comes out to be TRUE. This saves us the hassle of 3 extra variables.

Now, my question is this. How to program this in JAVA? How do I even get to know if the input does have a pattern like above? Or is it just an expression that I have to evaluate for the whole Truth Table? Like the one below

(p ∨ ¬q) ∧ (r ∨ (s ∧ (¬p ∨ u)))
Sam :

This is a well known NP-complete problem, see Boolean Satisfiability Problem.

This means there is no known polynomial time solution, but there are many >P solutions out there.

You will have to brute force it and short circuit where you can. (ex: if all operators are or and you find a true value you can stop computation)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=90184&siteId=1