Home > Back-end >  How to check if two out of three values are the same?
How to check if two out of three values are the same?

Time:03-01

I was wondering how to check if two out of three values are the same. My code right now is:

public static boolean twoOutOfThree(int a, int b, int c) {
          if ((a==b) || (b==c) || (a==c)) {
                return true;
            }else{
                return false;
            }
        }

This passes all of the tests that are true however when I test it for (0,0,0), it comes back as true instead of false. Any suggestions on what I'm doing wrong?

CodePudding user response:

When all 3 are the same, then a==b obviously is also true. So each 3 of the cases also needs to check that the 3rd one is different. So you need to change

((a==b) || (b==c) || (a==c))

to

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

Additional tip:
functions of this form

if (condition) {
    return true;
} else {
    return false;
}

Can be written much shorter by just doing

return condition;

So the end result is:

public static boolean twoOutOfThree(int a, int b, int c) {
    return ((a==b && b!=c) || (b==c && a!=c) || (a==c && b!=c));
}

CodePudding user response:

Here is a non-optimized solution.

The Set will get rid of duplicates, then just check its final size.

return new HashSet<Integer>(Arrays.asList(a,b,c)).size() == 2;

CodePudding user response:

You could add an extra case to your if statement:

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

There is probably a more efficient way to do this.

CodePudding user response:

You can add a variable called "count" for example , if any value is equal to another then you increment the count by 1 and then you can check if count is equal to 2

CodePudding user response:

You can count as the following solution

public static boolean twoOutOfThree(int a, int b, int c) {
    int count = 0;
    if (a == b) {
       count  = 1;
    }
    if (b == c) {
       count  = 1;
    }
    if (c == a)
       count  = 1;
    }
    if (count == 2) {
        return true;
    } else {
        return false;
    }
}

CodePudding user response:

Just create a Set and add your values in the set. Set always holds unique values only. So if you have 3 numbers and add them to a set and your set length is 3 that none of the numbers are equal to each other. If the length is 2 then 2 numbers where equal and if the length is 1 then all 3 are equal

CodePudding user response:

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

Only 10 operators made of

  • 3 AND
  • 1 OR
  • 1 NOT
  • 5 comparisons

I don't know if this is fastest. But if CPU core has multiple ALUs each doing comparisons in parallel, then this could get a boost.

  •  Tags:  
  • java
  • Related