'Combining of logical conditions in IF statement
I just notice the if condition below:
//1
if ((i >= 0) != (j >= 0))
return false;
is just a short way for:
//2
if((i>=0 && j < 0) || (i < 0 && j >=0))
return false;
Going from 1. to 2. takes some time to figure out, but how do we deduce the logic to go from 2. to 1.?
Solution 1:[1]
If we call (i >= 0) something arbitrary like A and (j >= 0) something else like B then it stands to reason that (i < 0) is just Not A (often shown as !A) and (j < 0) would be Not B or !B
Meaning this block:
if((i>=0 && j < 0) || (i < 0 && j >=0))
return false;
Can be represented as:
if ((A && !B) || (!A && B))
return false;
else // you haven't specified this part but it's implied
return true;
Now, if we approach this as:
How do we get to the true value?
Then you realise it's the same as:
if ((A && B) || (!A && !B))
return true;
else
return false;
Then we can call (A && B) something else like C; so it becomes:
if (C || !C)
return true;
else
return false;
So, expanding out again, we can get:
if (A && B)
return true;
else if (!(A && B))
return true;
else
return false;
So, that's:
if ((i >= 0) && (j >= 0))
return true;
else if (!( (i >= 0) && (j >= 0) ) )
return true;
else
return false;
Which can evaluate to:
if (True && True)
return true;
else if (False && False)
return true;
else
return false;
Showing that it's as simple as:
if ( (i >= 0) == (j >= 0) )
return true;
else // if ( (i >= 0) != (j >= 0) )
return false;
So, we've gone around the houses but we've worked our way down from statement 2 to statement 1.
NOTE: Adam's answer is more concise and is accurate from a pure logic perspective; this is more to provide a broader overview as I know that some people learn better when they can see the process.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
