Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a concise easy to read way of testing to see if two numbers out of three are equal?

Tags:

algorithm

Basically, if I have a function like so:

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 there are n numbers are equal out of a set? What about only three items? Is there a mathematical operation that I can take advantage of? I know that I can do an iterative approach to solve, I'm just curious if there are other ways to solve that are clearer.

Here is a break down of conditions because I'm having a hard time expressing 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
like image 862
Elijah Avatar asked Mar 21 '11 17:03

Elijah


People also ask

How can you tell if two values are the same?

The quickest way to compare two cells is with a formula that uses the equal sign. If the contents of cell A2 and cell B2 are the same, the result is TRUE. Note: Upper and lower case versions of the same letter are treated as equal, as you can see in the screen shot below.


2 Answers

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

def foo(a, b, c):
    return len(set((a, b, c))) == 2
like image 171
Andrew Clark Avatar answered Oct 13 '22 22:10

Andrew Clark


I don't think you're going to get any more efficient or concise than the manual way:

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

Or else this:

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

If a, b, and c are boolean only (0 or 1) values, then you can just do this:

return a+b+c == 1 || a+b+c == 2 // Either two are false, or two are true
like image 31
Eclipse Avatar answered Oct 13 '22 23:10

Eclipse