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 C#

2 Answers

0 votes
using System;
using System.Linq;

class Program
{
    /// <summary>
    /// Finds the N smallest values in a 2D matrix using a LINQ flatten-and-sort 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>
    public static int[] FindNSmallestLinq(int[,] matrix, int n)
    {
        // Guard clauses for null, empty array, or invalid element count
        if (matrix == null || matrix.Length == 0 || n <= 0) {
            return Array.Empty<int>();
        }

        // Cast converts the multidimensional array (int[,]) into an IEnumerable<int> sequence,
        // effectively flattening it without manual looping. OrderBy handles sorting, 
        // Take selects the first N elements, and ToArray materializes the final result.
        return matrix.Cast<int>()
                     .OrderBy(x => x)
                     .Take(n)
                     .ToArray();
    }

    /// <summary>
    /// Alternative high-performance implementation using Array.Sort.
    /// Flattens the array into memory and sorts in-place using IntroSort.
    /// </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>
    public static int[] FindNSmallestFast(int[,] matrix, int n)
    {
        if (matrix == null || matrix.Length == 0 || n <= 0) {
            return Array.Empty<int>();
        }

        // Allocate a 1D target buffer sized for all matrix elements
        int totalElements = matrix.Length;
        int[] flatArray = new int[totalElements];

        // Buffer.BlockCopy offers fast raw memory block copying to flatten 2D rectangular arrays
        Buffer.BlockCopy(matrix, 0, flatArray, 0, totalElements * sizeof(int));

        // Sort the flattened buffer in-place
        Array.Sort(flatArray);

        // Slice out the first N values using modern C# range/span syntax
        int targetCount = Math.Min(n, totalElements);
        return flatArray[..targetCount];
    }

    public static void Main()
    {
        // Sample 4x4 matrix initialization
        int[,] grid = {
            { 42, 12, 85,  3 },
            {  7, 99, 15, 23 },
            { 64,  1, 18, 30 },
            {  3, 55, 11, 90 }
        };

        Console.WriteLine("Input Matrix:");
        for (int r = 0; r < grid.GetLength(0); r++)
        {
            Console.Write("  [ ");
            for (int c = 0; c < grid.GetLength(1); c++) {
                Console.Write($"{grid[r, c],3}");
                if (c < grid.GetLength(1) - 1) Console.Write(",");
            }
            Console.WriteLine(" ]");
        }
        Console.WriteLine();

        int count = 5;
        Console.WriteLine($"Finding the {count} smallest values (LINQ):");
        int[] smallestValues = FindNSmallestLinq(grid, count);
        Console.WriteLine($"[{string.Join(", ", smallestValues)}]");
    }
}


/*
run:

Input Matrix:
  [  42, 12, 85,  3 ]
  [   7, 99, 15, 23 ]
  [  64,  1, 18, 30 ]
  [   3, 55, 11, 90 ]

Finding the 5 smallest values (LINQ):
[1, 3, 3, 7, 11]

*/

 



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

class Program
{
    /*
        Find the N smallest values in a 2D array.

        Approach:
        1. Flatten the 2D array into a single sequence.
        2. Sort the sequence.
        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
    static List<int> Flatten(int[,] matrix)
    {
        var result = new List<int>(matrix.Length);

        // Iterate through the matrix in row‑major order
        for (int r = 0; r < matrix.GetLength(0); r++)
        {
            for (int c = 0; c < matrix.GetLength(1); c++) {
                result.Add(matrix[r, c]);
            }
        }

        return result;
    }

    // Extract the N smallest values
    static List<int> SmallestN(int[,] matrix, int n)
    {
        var flat = Flatten(matrix);

        // Sort and take the first N values
        return flat
            .OrderBy(x => x)
            .Take(n)
            .ToList();
    }

    static void Main()
    {
        int[,] matrix = {
            { 42, 12, 85,  3 },
            {  7, 99, 15, 23 },
            { 64,  1, 18, 30 },
            {  3, 55, 11, 90 }
        };

        int n = 5;

        var values = SmallestN(matrix, n);

        Console.WriteLine($"The {n} smallest values:");
        foreach (var v in values)
        {
            Console.Write(v + " ");
        }
        Console.WriteLine();
    }
}


/*
run:

The 5 smallest values:
1 3 3 7 11 

*/

 



answered 2 days ago by avibootz
...