Reputation: 814
I have a conditional if statement like this
if ((a && (b || c)) ||
(b && (a || c))) {
}
basically what I'm trying to achieve is that I can only have one option true, but two is not ok!
Can it be more simplified, looks redundant to me! Or should I extract it to a function?
edit
if (a && !b && !c) // process a
if (b && !a && !c) // process b
if (c && !a && !b) // process c
if (!a && !b && c!) // none present exception
else {} // more than one case exception
Upvotes: 0
Views: 133
Reputation: 5239
Yes it can be simpler, this would be more than enough since a && b
will give the same result as b && a
:
if (a && b || c) {
}
Note: the original question was completely different, and asked to simplify the following expression:
if ((a && b || c) ||
(b && a || c)) {
}
Upvotes: 5
Reputation: 3691
Following the comment and the edit, each line is the development of the previous one:
(a && (b || c)) || (b && (a || c))
((a && b) || (a && c)) || ((a && b) || (b && c))
(a && b) || (a && c) || (a && b) || (b && c)
You have a duplicate, so you can turn it to: (those lines are equals)
(a && b) || (a && c) || (b && c)
(a && (b ||c)) || (b&&c)
Upvotes: 2
Reputation: 91
if (c || (a && b) {
...
}
The 2 large conditions are the same... ´&&` is commutative
Upvotes: 0
Reputation: 78
&& operator is Commutative so a && b or b && a results in same output.
Now your condition becomes like this
if ((a && b || c) ||
(a && b || c)) {
}
|| operator is Idempotent so x || x results x
your expression becomes (a && b) || c
But in java && and || operators exhibit "short-circuiting" behavior
First operand will be evaluated first and then second operand will be evaluated only if need so you can choose which operand to keep first based on operand complexity.
Upvotes: 1