Noah
Noah

Reputation: 41

Java - Multidimensional Arrays How to test an array for all unique values

I'm trying to test a multidimensional array to see if contains any duplicate values. If it does I would like the method to return false. Otherwise I would like it to return true.

Here is my current code. Where is my logic wrong?

public static boolean isUnique(int[][] array2, int num) {

    for (int i = 0; i < array2.length - 1; i++) {
        for (int j = i + 1; j < array2.length; j++) {
            if (array2[i] == array2[j]) {
                return false;
            }
        }
    }
    return true;
}

Upvotes: 0

Views: 810

Answers (2)

nbrooks
nbrooks

Reputation: 18233

Right now your code is checking whether any of the arrays inside array2 are the same. array2[i] and array2[j] are both referring to arrays, because array2 is an array of arrays.

Instead, you want to look at the values inside of each of those arrays. Since you want to fail on any repeated value anywhere in the grid, you're effectively trying to flatten the structure into one collection, and check for duplicates in that.

A HashSet is the best data structure to use in this case. Traverse the entire grid, row-by-row, adding values into your new struture. If you encounter a duplicate, return false:

public static boolean isUnique(int[][] array2) {
    Set<Integer> values = new HashSet<>();

    for (int i = 0; i < array2.length; i++) {
        for (int j = 0; j < array2[i].length; j++) {
            if (!values.add(array2[i][j])) {
                return false;
            }
        }
    }

    return true;
}

Some things to note here:

  • The set's add method will return false if you attempt to add a duplicate to the collection, so that's wrapped in an if statement for a simple, fail-fast stopping condition.

  • The sizes of each of the inner arrays are completely independent from the size of the outer array, so you still want to loop from 0 to the length of the array (when you're using <, you don't need the length - 1).

Upvotes: 1

Erin Owen
Erin Owen

Reputation: 66

Your current implementation is checking whether two rows are the same (this is a reference based check, rather than a value.) This means that it asks 'Are array2[i] and array2[j] the same address in memory, rather than do they contain the same things.

If you want to see whether the rows are unique you'd use array2[i].equals(array2[j]) instead of array2[i] == array2[j].

If you wanted to check for unique elements (array[i][j] != array2[i+m][j+n] where !(m == n == 0)) you'd need to iterate through both levels in a

for (int i = 0; i < array2.length; i++) {
    for (int j = 0; j < array2[i].length; j++) {
        // compare array2[i][j] to all other array2[m][n] here.
    }
}

Upvotes: 1

Related Questions