'I'm trying to make a function that takes a 2d array as a parameter and outputs a normal array containing every unique number, in java

The function needs to have a 2d array as a parameter and then return a normal array with all the unique numbers. If the 2d array is

[
[1,1],
[4,2]
]

then it should output

[1,4,2]

I'm still pretty new to coding so I'm finding it difficult to wrap my head around this. this is what I have currently

static void getUniqueNumbers(int arr[], int n) {
    for (int i = 0; i < n; i++) {

        int j;
        for (j = 0; j < i; j++)
            if (arr[i] == arr[j])
                break;
        if (i == j)
            System.out.print(arr[i] + " ");
    }
}

it works for a single array but I don't know how to adjust it to work with a 2d array.



Solution 1:[1]

Without using anything too fancy:

static List<Integer> getUniqueNumbers(int arr2d[][]) {
    List<Integer> unique = new ArrayList<Integer>();
    for(int[] row : arr2d) {
        for(int x : row) {
            if (!unique.contains(x)) { 
                unique.add(x);
            }
        }
    }
    return unique;
}

You can directly output the contents of a List:

List<Integer> results = getUniqueNumbers(arr);
System.out.println(results);

You'd get something like:

[1, 4, 2]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Idle_Mind