Search code examples
javaoutliersparity

Find The Parity Outlier CodeWars


So I decided to go to codewars to just brush up a little bit on java and I have this problem to solve:

You are given an array (which will have a length of at least 3, but could be very large) containing integers. The array is either entirely comprised of odd integers or entirely comprised of even integers except for a single integer N. Write a method that takes the array as an argument and returns this "outlier" N.

Here are my test cases:

public class OutlierTest{
         @Test
         public void testExample() {
             int[] exampleTest1 = {2,6,8,-10,3}; 
             int[] exampleTest2 = {206847684,1056521,7,17,1901,21104421,7,1,35521,1,7781}; 
             int[] exampleTest3 = {Integer.MAX_VALUE, 0, 1};
             assertEquals(3, FindOutlier.find(exampleTest1));
             assertEquals(206847684, FindOutlier.find(exampleTest2));
             assertEquals(0, FindOutlier.find(exampleTest3));
         }}

And here is the code i used to solve the problem:

            public class FindOutlier{
              static int find(int[] integers){

              int numerOfOdds = 0;
              int numberOfEvens = 0;
              int integerOutlier;


                for(int i = 0; i < integers.length ;i++){
                  if ( integers[i]%2 == 0){
                    numberOfEvens++;
                  }else{
                    numerOfOdds++;
                  }  
                }

                if ( numberOfEvens > numerOfOdds){
                  integerOutlier = 1;    
                }else{
                  integerOutlier = 0;
                }

                for(int i = 0; i < integers.length; i++){
                  if ((integers[i]%2) == integerOutlier){
                    return integers[i];
                  }
                }

              return 0;
            }}

Essentially what the code does is loops through the array to find the outlying parity. Then loops again to determine the outlying integer. This code passes all of its testcases. However, when I try to attempt to submit the code it tells me that it is expecting -3 but got 0.

Can anyone help me find the fault in my logic here? It's kinda frustrating because it doesn't tell me what the array its testing for so I cant trace my code to find the fault.

Excuse me for the typos and if they code isn't the most efficient, I probably would have used ArrayLists, but it seems like CodeWars doesn't allow for ArrayLists...


Solution

  • Well, your math has a bug: -3 % 2 == -1, so when a negative odd number is the outlier it fails. Change your second loop to

    for(int i = 0; i < integers.length; i++){
      if (Math.abs(integers[i]%2) == integerOutlier){
        return integers[i];
      }
    }