What is a short, easy-to-read testing tool to see if two numbers out of three are equal?

Basically, if I have a function like this:

function foo (int a, int b, int c) { return true if two out of the three variables are true otherwise false } 

Is there a simple and concise way to find out if n numbers from a set are equal? How about only three items? Is there a mathematical operation that I can use? I know that I can take an iterative approach to the solution, I'm just wondering if there are other solutions that are clearer.

Here is the breakdown of the conditions because it is difficult for me to express the problem:

 if no numbers are equal, return false if two numbers out of three are equal, return true if all three numbers are equal, return false 
+7
source share
6 answers

One method is to add parameters to the set, and then see if the length of this set is 2 (or less than 3 if you return true if they are all equal). For example, in Python:

 def foo(a, b, c): return len(set((a, b, c))) == 2 
+12
source

I do not think that you will make it more efficient or concise than the manual:

 if a == b return b != c else return b == c || a == c 

Or else:

 return ((a == b) || (a==c) || (b==c)) && ((a!=b) || (a!=c) || (b!=c)) 

If the values ​​a, b and c are boolean values ​​(0 or 1), you can simply do this:

 return a+b+c == 1 || a+b+c == 2 // Either two are false, or two are true 
+5
source

In C or C ++ you can:

  return ((a == b) | (b == c) | (a == c));

or return the number of matches:

  return ((a == b) + (b == c) + (a == c));

In the case when you want to specify only 2:

  return (((a == b) + (b == c) + (a == c)) == 1);

We like to use bit wise or | not logical || for performance. This is all based on a standard indicating that comparisons return 1 for TRUE and 0 for FALSE.

+3
source

if the input variables are logical, than you could build a truth table and minimize the resulting function, for example, using a KV diagram

 abcf(a,b,c) 0 0 0 0 0 0 1 0 0 1 0 0 0 1 1 1 1 0 0 0 1 0 1 1 1 1 0 1 1 1 1 1 

As a result of minimization, the result is returned

  (c and a) or (b and a) or (c and b) 

KV-Diagram can easily handle up to 4 variables (with experience, possibly 6 variables). More logical data needs more complex methods.

+2
source

In C you can use

 return ((a == b) || (b == c)) ^ (a == c); 
+2
source
 int difference = a-(bc); if(a==0 && b==0 && c==0) return false; if((difference == a) /*b=c*/ || (difference == c) /*a=b*/ || (difference == (2*ab)) /*a=c*/) return true; return false; 
0
source

All Articles