Alayna Arnold Alayna Arnold - 3 years ago 139
Java Question

Counting Unique doubles in an Array in Java (Brute Force)

Through brute force the code is supposed to return the number of unique values in an array, but it always returns 0?

public static int numUnique (double[] list) {

int unique = 0;

for (int i = 0 - 1; i > list.length; i--) {
for (int j = 1; j < list.length; j++) {
if (list[i] == list[j] && i != j) {
unique += 1;
}
}

}

return unique;

Answer Source

You must iterate through all numbers and check if they appear more then one time in the same array

public static int numUnique (double[] list) {
    int unique = 0;
    for (int i = 0; i < list.length; i++) {
        boolean isUnique = true;
        for (int j = i + 1; j < list.length; j++) {
            if (list[i] == list[j]) {
               isUnique = false;
            }
        }
        if (isUnique) unique+=1;

    }
    return unique;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download