在c#中查找二维数组中的最小值及其索引

时间:2017-01-07 21:23:05

标签: c# arrays 2d min

我试图在数组中找到min值和它的索引,定义如下:

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

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

2 个答案:

答案 0 :(得分: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]子阵列的最小值(请参阅下面的评论),您可以简化代码(放弃一个循环)

     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;
       }
     }

答案 1 :(得分:0)

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

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是最大值,它将返回它们的值和索引。