Search code examples
javaarraysfind-occurrences

how to count and print out only duplicates?


I know how to go through whole array, but I only need number of duplicate occurrences. I'm at beginners level, so just basic use of loops and arrays.

int[] array = {12, 23, -22, 0, 43, 545, -4, -55, 43, 12, 0, -999, -87};

for (int i = 0; i < array.length; i++) {
    int count = 0;
    for (int j = 0; j < array.length; j++) {
        count++;   
    }
    System.out.println(array[i] + "\toccurs\t" + count + "X");
}

Solution

  • You can do better if you use more than just loops and arrays, but a simple algorithm would be to use two nested for loops, and put an if statement inside that increments a counter when a duplicate is found.

    int[] array = {12, 23, -22, 0, 43, 545, -4, -55, 43, 12, 0, -999, -87};
    
    for (int i = 0; i < array.length - 1; i++) {
        int count = 1;
        for (int j = i + 1; j < array.length; j++) {
            if (array[i] == array[j]) {
                count++;
            }
        }
        if (count > 1) {
            System.out.println(array[i] + "\toccurs\t" + count + " times");
        }
    }