How to create a sorted unique array from a matrix in C#

1 Answer

0 votes
using System;
using System.Linq;

/*
    Create a sorted unique array (arr) from a matrix (arr of arr).
    Steps:
      1. Flatten matrix into arr
      2. Sort arr (Array.Sort)
      3. Remove duplicates (Distinct)
*/

class SortedUniqueArrFromMatrix
{
    // Flatten + sort + unique
    static int[] MakeSortedUniqueArr(int[,] mat)
    {
        int rows = mat.GetLength(0);
        int cols = mat.GetLength(1);
        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 r = 0; r < rows; r++) {
            for (int c = 0; c < cols; c++) {
                arr[k++] = mat[r, c];
            }
        }

        // Sort arr
        Array.Sort(arr);

        // Remove duplicates and return resized arr
        return arr.Distinct().ToArray();
    }

    static void Main()
    {
        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);

        foreach (int x in arr)
            Console.Write(x + " ");
    }
}



/*
run:

1 2 3 4 5 7 8 9 17 88

*/

 



answered 6 days ago by avibootz
edited 6 days ago by avibootz
...