【问题标题】:finding min value and its index in 2D array in c# [closed]在 C# 中查找二维数组中的最小值及其索引 [关闭]
【发布时间】:2017-05-22 10:57:19
【问题描述】:

我正在尝试找到最小值并将其索引在一个定义如下的数组中:

double[,] Neighbour_Array=new double [4,500];

什么是最短的路?你能帮帮我吗?

【问题讨论】:

  • 如果是任意数组,则必须扫描数组
  • 忘记最短路径。向我们展示您到目前为止所做的事情。您是否设法做到了最长的方式?
  • @Mahdieh 请edit 发布,而不是将代码发布为 cmets。

标签: c# arrays 2d min


【解决方案1】:

一般情况下,对于任意数组,你必须扫描整个数组:

  double[,] Neighbour_Array = new double[4, 500];

  ...

  double minValue = double.PositiveInfinity;
  int minFirstIndex = -1;
  int minSecondIndex = -1;

  // Comparison with 0 is faster than with GetLength()
  for (int i = Neighbour_Array.GetLength(0) - 1; i >= 0; --i)
    for (int j = Neighbour_Array.GetLength(1) - 1; j >= 0; --j) {
      double value = Neighbour_Array[i, j];

      if (value <= minValue) {
        minFirstIndex = i;
        minSecondIndex = j;

        minValue = value;
      }
    }

编辑:如果您想找出Neighbour_Array[2,i] 子数组的最小值(请参阅下面的 cmets),您可以将代码简化(放一个循环)到

     double minValue = double.PositiveInfinity;
     int minIndex = -1; 

     // Comparison with 0 is faster than with GetLength()
     for (int i = Neighbour_Array.GetLength(1) - 1; i >= 0; --i) {
       // please notice, that the 1st index is fixed 
       double value = Neighbour_Array[2, i];

       if (value <= minValue) {
         minIndex = i;

         minValue = value;
       }
     }

【讨论】:

  • 你是对的,我忘了提到我正在尝试在数组的第二维中找到最小值,我的意思是在所有 Neighbour_Array[2,i] 中。谢谢你的回答。
  • @Mahdieh 请不要使用二维数组来伪造类列表...至少不要向公众发布此类问题 - 使用 class Pos {double x,y,z,v} ;Pos[500]; 或类似的东西来公开可见的代码.
【解决方案2】:

我不会说它高效,但它是我能想到的最短的代码量:

var len = neighbors.GetLength(1);
var flatten = neighbors.Cast<double>();
var max = flatten.Max();
var maxes = flatten
   .Select((v, i) => new { v, i1=i/len, i2=i-(len*(i/len)) })
   .Where(n => n.v == max);

它返回所有等于最大值的值和索引。 因此,如果您的数组中有两个 5,并且 5 是最大值,它将返回它们的值和索引。

【讨论】:

    猜你喜欢
    • 2016-03-11
    • 2016-02-24
    • 1970-01-01
    • 2018-07-05
    • 2014-03-05
    • 2019-07-05
    • 2015-04-06
    • 2020-09-05
    • 2016-11-05
    相关资源
    最近更新 更多