How to create a sorted unique array from a matrix in VB.NET

1 Answer

0 votes
Imports System
Imports 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)
'

Module SortedUniqueArrFromMatrix

    ' Flatten + sort + unique
    Function MakeSortedUniqueArr(mat As Integer(,)) As Integer()

        Dim rows As Integer = mat.GetLength(0)
        Dim cols As Integer = mat.GetLength(1)
        Dim total As Integer = rows * cols

        ' Allocate arr large enough for all elements
        Dim arr(total - 1) As Integer

        ' Flatten matrix into arr
        Dim k As Integer = 0
        For r As Integer = 0 To rows - 1
            For c As Integer = 0 To cols - 1
                arr(k) = mat(r, c)
                k += 1
            Next
        Next

        ' Sort arr
        Array.Sort(arr)

        ' Remove duplicates and return resized arr
        Return arr.Distinct().ToArray()
    End Function

    Sub Main()

        Dim mat As Integer(,) = {
            {5, 1, 17, 3, 8, 2, 1, 9},
            {3, 5, 7, 4, 2, 3, 4, 1},
            {9, 1, 8, 2, 3, 88, 17, 5}
        }

        Dim arr As Integer() = MakeSortedUniqueArr(mat)

        For Each x In arr
            Console.Write(x & " ")
        Next

    End Sub

End Module



' run:
'
' 1 2 3 4 5 7 8 9 17 88
'

 



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