Imports System
Module Program
''' <summary>
''' Flattens a 2D matrix into a 1D array using nested loops.
''' </summary>
''' <param name="matrix">The input 2D array of integers.</param>
''' <returns>A single-dimensional array containing all matrix elements.</returns>
Function FlattenMatrix(matrix(,) As Integer) As Integer()
Dim rows As Integer = matrix.GetLength(0)
Dim cols As Integer = matrix.GetLength(1)
Dim flatArray(rows * cols - 1) As Integer
Dim index As Integer = 0
For r As Integer = 0 to rows - 1
For c As Integer = 0 to cols - 1
flatArray(index) = matrix(r, c)
index += 1
Next
Next
Return flatArray
End Function
''' <summary>
''' Finds the N smallest values in a 2D array using the flatten, sort, and slice approach.
''' </summary>
''' <param name="matrix">The 2D input array of integers.</param>
''' <param name="n">The number of smallest elements to retrieve.</param>
''' <returns>An array containing the N smallest elements in ascending order.</returns>
Function FindNSmallest(matrix(,) As Integer, n As Integer) As Integer()
' Guard clauses for empty array or invalid count
If matrix Is Nothing OrElse matrix.Length = 0 OrElse n <= 0 Then
Return Array.Empty(Of Integer)()
End If
' Step 1: Flatten the 2D matrix into a 1D array
Dim flatArray As Integer() = FlattenMatrix(matrix)
' Step 2: Sort the array in-place using the highly optimized Array.Sort method
Array.Sort(flatArray)
' Step 3: Determine target slice length (clamp to total available elements)
Dim targetCount As Integer = Math.Min(n, flatArray.Length)
' Step 4: Extract the first N items using built-in Array segment copy
Dim result(targetCount - 1) As Integer
Array.Copy(flatArray, result, targetCount)
Return result
End Function
Sub Main()
' Sample 4x4 matrix initialization
Dim grid(,) As Integer = {
{42, 12, 85, 3},
{ 7, 99, 15, 23},
{64, 1, 18, 30},
{ 3, 55, 11, 90}
}
Console.WriteLine("Input Matrix:")
For r As Integer = 0 To grid.GetLength(0) - 1
Console.Write(" [ ")
For c As Integer = 0 To grid.GetLength(1) - 1
Console.Write($"{grid(r, c),3}")
If c < grid.GetLength(1) - 1 Then Console.Write(",")
Next
Console.WriteLine(" ]")
Next
Console.WriteLine()
Dim count As Integer = 5
Console.WriteLine($"Finding the {count} smallest values:")
' Extract N smallest values
Dim smallestValues As Integer() = FindNSmallest(grid, count)
' Display result
Console.WriteLine($"[{String.Join(", ", smallestValues)}]")
End Sub
End Module
' run:
'
' Input Matrix:
' [ 42, 12, 85, 3 ]
' [ 7, 99, 15, 23 ]
' [ 64, 1, 18, 30 ]
' [ 3, 55, 11, 90 ]
'
' Finding the 5 smallest values:
' [1, 3, 3, 7, 11]
'