Simplify three way comparison a < b < c || b < c < a || c < a < b;

214 views Asked by At

Is there a shorter way to compute this boolean expression?

a < b < c || b < c < a || c < a < b

In JavaScript this would be:

a < b && b < c || b < c && c < a || c < a && a < b

Is there some useful maths or boolean algebra trick which would make this less cumbersome?

a, b and c are all numbers. In my particular use case, they are guaranteed to be distinct.

(For additional context, it arose in the process of answering this question)

1

There are 1 answers

0
Bergi On BEST ANSWER

You have 3 different boolean comparisons out of which you want 2 to hold. (Strictly, 2 or more, but in your case you can never have all 3). So you can write

a < b && b < c || b < c && c < a || c < a && a < b

as

(a < b) + (b < c) + (c < a) == 2