Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,683 questions

55,435 answers

573 users

How to find the N smallest values in a 2D array in VB.NET

2 Answers

0 votes
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]
' 

 



answered 2 days ago by avibootz
0 votes
Imports System
Imports System.Collections.Generic
Imports System.Linq

Module Program

    '
    '   Find the N smallest values in a 2D array.
    '
    '   Approach:
    '   1. Flatten the 2D array into a single list.
    '   2. Sort the list.
    '   3. Take the first N values.
    '
    '   This keeps the code readable and expressive while relying on
    '   efficient built‑in operations. For extremely large datasets,
    '   a heap‑based approach could be used, but LINQ is ideal here.
    '

    ' Flatten a 2D array into a single list
    Function Flatten(matrix As Integer(,)) As List(Of Integer)
        Dim result As New List(Of Integer)(matrix.Length)

        ' Iterate through the matrix in row‑major order
        For r = 0 To matrix.GetLength(0) - 1
            For c = 0 To matrix.GetLength(1) - 1
                result.Add(matrix(r, c))
            Next
        Next

        Return result
    End Function

    ' Extract the N smallest values
    Function SmallestN(matrix As Integer(,), n As Integer) As List(Of Integer)
        Dim flat = Flatten(matrix)

        ' Sort and take the first N values
        Return flat _
            .OrderBy(Function(x) x) _
            .Take(n) _
            .ToList()
    End Function

    Sub Main()

        ' Example 2D array
        Dim matrix As Integer(,) = {
            {42, 12, 85, 3},
            {7, 99, 15, 23},
            {64, 1, 18, 30},
            {3, 55, 11, 90}
        }

        Dim n As Integer = 5

        Dim values = SmallestN(matrix, n)

        Console.WriteLine($"The {n} smallest values:")
        For Each v In values
            Console.Write(v & " ")
        Next
        Console.WriteLine()

    End Sub

End Module



'
' run:
'
' The 5 smallest values:
' 1 3 3 7 11
'

 



answered 2 days ago by avibootz
...