HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaModerate

Count the number of unique elements in a sorted array

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
uniquethenumberelementsarraysortedcount

Problem

Write a method named numUnique that accepts a sorted array of integers as a parameter and that returns the number of unique values in the array. The array is guaranteed to be in sorted order, which means that duplicates will be grouped together.

I'm mainly concerned with following proper conventions and maximizing readability; both of which I feel I know little about. In the last question I posted, I learned a bit about structuring if-statements. How can I think about these statements so that it's easier for me to write them, as well as easier for others to read them? Is there a sort of PEMDAS of programming logic that would help me understand writing conditional code with precedence? Any feedback is appreciated!

public static int numUnique(int[] array){
    if(array.length > 0){
        int countUnique = 1;
        for(int i = 0; i < array.length - 1; i++){
            if(array[i] != array[i+1]){
                countUnique++;
            }
        }
        return countUnique;
    } else {
        return 0;
    }
}

Solution

Just a few minor suggestions:

  • If you invert the condition on the length, then you can reduce the level of nesting, which is slightly easier to read



  • An array will never have a negative length. It's pure paranoia to check for array.length



  • The spacing is not perfect. Use an IDE to reformat the code



  • This maybe a matter of taste, but I would rename countUnique to simply count, and the method from numUnique to countUnique`



Putting it together:

public static int countUnique(int[] array) {
    if (array.length == 0) {
        return 0;
    }
    int count = 1;
    for (int i = 0; i < array.length - 1; i++) {
        if (array[i] != array[i + 1]) {
            count++;
        }
    }
    return count;
}

Code Snippets

public static int countUnique(int[] array) {
    if (array.length == 0) {
        return 0;
    }
    int count = 1;
    for (int i = 0; i < array.length - 1; i++) {
        if (array[i] != array[i + 1]) {
            count++;
        }
    }
    return count;
}

Context

StackExchange Code Review Q#114073, answer score: 10

Revisions (0)

No revisions yet.