Code that should count all pairs in an array doesnt work corectly

Pat :

My code should count all pairs in a given array. For example if there is an array: 2,3,4,2,3,2,2, the number of pairs is: (2,2), (2,2), (3,3) -> 3 pairs.

This is the task on codewars.com.
https://www.codewars.com/kata/find-all-pairs-1/train/java

But my code dont pass random test and I have no idea what I am doing wrong.

public static int duplicates(int[] array)
{
    if (array.length == 0 || array.length == 1)
        return 0; 

    int numberOfPairs = 0;
    int counted;

    for (int num : array) {
        counted = 0;
        for (int num2 : array) {
            if (num == num2) {
                counted++;
                if (counted >= 2) {
                    numberOfPairs++;
                    break;
                }
            }
        }
    }

    return numberOfPairs / 2;
}
Nexevis :

I used Arrays.sort to make it easier.

Here is the logic I used step by step:

  1. First the array is sorted in ascending order before the loop.
  2. In the loop, check to see if the next number is the same as the current number.
  3. If they are the same, increment the count and iterate the loop by 2 to skip the number that was already used.

  4. If they are not the same iterate the loop only once because the next value has not been used yet.

Here is the implementation of the logic below:

public static int duplicates(int[] array)
{
   int numberOfPairs = 0;

   Arrays.sort(array);
   for (int k = 0; k < array.length - 1; k++) 
   {
       if (array[k] == array[k + 1])
       {
           numberOfPairs++;
           k++;
       }
   }
   return numberOfPairs;
}

I tested it with a few different cases and it seems to be working.

Test Run:

int [] arr = {2, 3, 4, 2, 3, 2, 2, 2, 4, 4, 6, 7, 6 ,7 ,7, 7};
System.out.println("Duplicates: " + duplicates(arr));

Duplicates: 7

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=129555&siteId=1