How to create a sorted unique array from a matrix in Java

1 Answer

0 votes
import java.util.Arrays;

/**
    Create a sorted unique array (arr) from a matrix (arr of arr).
    Steps:
      1. Flatten matrix into arr
      2. Sort arr (Arrays.sort)
      3. Remove duplicates in-place
*/

public class SortedUniqueArrFromMatrix {

    // Flatten + sort + unique
    static int[] makeSortedUniqueArr(int[][] mat) {

        int rows = mat.length;
        int cols = mat[0].length;
        int total = rows * cols;

        // Allocate arr large enough for all elements
        int[] arr = new int[total];

        // Flatten matrix into arr
        int k = 0;
        for (int[] slc : mat) {          // slc = slice (row)
            for (int x : slc) {
                arr[k++] = x;
            }
        }

        // Sort arr
        Arrays.sort(arr);

        // Remove duplicates in-place
        int u = 0;
        for (int i = 0; i < total; i++) {
            if (i == 0 || arr[i] != arr[i - 1]) {
                arr[u++] = arr[i];
            }
        }

        // Return arr resized to unique count
        return Arrays.copyOf(arr, u);
    }

    public static void main(String[] args) {

        int[][] mat = {
            {5, 1, 17, 3, 8, 2, 1, 9},
            {3, 5, 7, 4, 2, 3, 4, 1},
            {9, 1, 8, 2, 3, 88, 17, 5}
        };

        int[] arr = makeSortedUniqueArr(mat);

        for (int x : arr) {
            System.out.print(x + " ");
        }
    }
}



/*
run:

1 2 3 4 5 7 8 9 17 88

*/

 



answered 6 days ago by avibootz
...