{
ans += (a[i] > a[j]) != (b[i] > b[j]);
//ans += ((a[i] > a[j]) && (b[j] > b[i])) || ((a[j] > a[i]) && (b[i] > b[j]));
}
What you see above is a snippet I took from some where. There are two logic expressions. Supposedly, the one commented out is the same as the one not commented out.
How do you get from:
((a[i] > a[j]) && (b[j] > b[i])) || ((a[j] > a[i]) && (b[i] > b[j]))
to something like this
(a[i] > a[j]) != (b[i] > b[j])
Are there any guides or books for these kind of logic expression simplifications?
The code you posted is right if you assume that
Meaning that for some reason, you’re ignoring equality.
With this in mind, let’s say that:
Then you have:
Which, since we’re ignoring equality, is the same as:
If you take a closer look, you’ll see that the expressions are repeated, so they can be simplified:
Then:
Which means either A or B, but no both
This is a known boolean operation called XOR, which in your case is the same as different (!=)
Therefore:
And expanding:
So:
Hope it’s clear now.