c# - 如何在二维动态数组中找到最小值
问题描述
我试图在动态二维数组中找到最小的数字,但我遇到了一个障碍,无法弄清楚这是如何完成的。我已经完成了所有设置并填充了值。
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 数组中设置一组随机数中的最小值。
解决方案
首先,格式化你的代码:难读的代码很难调试。
通常,我们可以在 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}");
推荐阅读
- c# - C++ DLL 的函数不在 WPF 中输出文本
- python - 是否可以使用遗传算法随机限制变量数量?
- javascript - 如果是对象,如何检查空值并替换它?
- r - 在 tibble 中寻求变异的帮助
- kendo-ui - 如果 Kendo Grid 中一个单元格的验证失败,如何允许编辑其他单元格?
- sql-server - SSRS:显示数据库中 varbinary 列的图像
- wordpress - Colormag wp 主题页脚自定义
- javascript - 我正在尝试从数组中获取图像以使用 Vue.js 显示。我是在犯语法错误还是错过了什么?
- vue.js - 如何访问包装器 Highcharts vue 的方法?
- javascript - 从反应私有路由中的axios调用返回true或false