首页 > 解决方案 > 如何在二维动态数组中找到最小值

问题描述

我试图在动态二维数组中找到最小的数字,但我遇到了一个障碍,无法弄清楚这是如何完成的。我已经完成了所有设置并填充了值。

        using System;

namespace _2D_Array
{
   class Program
   {
       static void Main(string[] args)
       {
           // Create integers n and r and set up the 2D array

           int n = 5;
           int[,] a;
           int R = 50;
           int x;
           
           a = new int[n + 1, n + 1];

           // Create number input randomizer

           Random r = new Random();
           for (int i = 1; i <= n; ++i)
               for (int j = 1; j <= n; ++j)
                   a[i, j] = r.Next(1, R);

           // Print array with random numbers to screen to check set up is correct for i and j

           Console.Write("   ");
           for (int i = 1; i <= n; ++i)
               Console.Write(i.ToString("00" + " "));
           Console.WriteLine();
           Console.WriteLine();
           for (int i = 1; i <= n; ++i)
           {
               Console.Write(i.ToString("00" + " "));
               for (int j = 1; j <= n; ++j)
                   Console.Write(a[i, j].ToString("00" + " "));
               Console.WriteLine();
           }
           // Get Search Value

           Console.Write("What's the value to look for? ");
           x = int.Parse(Console.ReadLine());

           // look through the array

           for (int i = 1; i <= n; ++i)
           {
               for (int j = 1; j <= n; ++j)

           // If the element is found
                   if (a[i, j] == x)
                   {
                       Console.Write("Element found at (" + i + ", " + j + ")\n");
                   }
               }
           Console.Write(" Element not found");
           
   ```

这就是我到目前为止所拥有的一切。最后,我希望在我的 5x5 数组中设置一组随机数中的最小值。




标签: c#

解决方案


首先,格式化你的代码:难读的代码很难调试。

通常,我们可以在 Linq 的帮助下查询数组:

  using System.Linq;

  ... 

  int min = a.OfType<int>().Min();       

  Console.Write($"The smallest element is {min}");

如果你想要好的旧嵌套循环:

  // not 0! What if min = 123?
  // Another possibility is min = a[0, 0]; - min is the 1st item 
  int min = int.MaxValue; 

  // note a.GetLength(0), a.GetLength(0): n is redundant here
  // and there's no guarantee that we have a square array
  for (int r = 0; r < a.GetLength(0); ++r)
    for (int c = 0; c < a.GetLength(1); ++c)
      min = Math.Min(min, a[r, c]); 

  Console.Write($"The smallest element is {min}");

推荐阅读