2010-07-15 62 views
7

那麼簡單的問題(也許不是一個簡單的答案?)查找二維數組中元素的位置?這裏

說我有一個二維數組

[0] [1] [2] 
[3] [4] [5] 
[6] [7] [8] 

現在假設我想要得到6

我知道電話號碼的位置與一維數組我可以使用Array.indexOf(),但我的選擇將與二維數組?

謝謝!

+0

我假設你指的是2D陣列('INT [,]'),而不是一個交錯數組('INT [] []' ) – SLaks 2010-07-15 23:58:21

回答

19

我想說的是這樣的:

public static Tuple<int, int> CoordinatesOf<T>(this T[,] matrix, T value) 
{ 
    int w = matrix.GetLength(0); // width 
    int h = matrix.GetLength(1); // height 

    for (int x = 0; x < w; ++x) 
    { 
     for (int y = 0; y < h; ++y) 
     { 
      if (matrix[x, y].Equals(value)) 
       return Tuple.Create(x, y); 
     } 
    } 

    return Tuple.Create(-1, -1); 
} 
+0

在這種情況下,我更喜歡創建一個類來表示結果,而不是使用Tuple,因爲Tuple並不傳達返回的內容。當你在看線Tuple coordinate = matrix.CoordinatesOf(5)時,你可以很容易地猜出它是一個座標/點,但是一旦該值在系統中移動,它就變成了一個Tuple,讓一些可憐的開發者跟蹤來源去了解Tuple 究竟代表什麼。 – 2016-10-28 17:59:27

1

下面是應該找到一個數組的索引與任意等級的方法。

...添加上/下範圍界限每秩

public static class Tools 
{ 
    public static int[] FindIndex(this Array haystack, object needle) 
    { 
     if (haystack.Rank == 1) 
      return new[] { Array.IndexOf(haystack, needle) }; 

     var found = haystack.OfType<object>() 
          .Select((v, i) => new { v, i }) 
          .FirstOrDefault(s => s.v.Equals(needle)); 
     if (found == null) 
      throw new Exception("needle not found in set"); 

     var indexes = new int[haystack.Rank]; 
     var last = found.i; 
     var lastLength = Enumerable.Range(0, haystack.Rank) 
            .Aggregate(1, 
             (a, v) => a * haystack.GetLength(v)); 
     for (var rank =0; rank < haystack.Rank; rank++) 
     { 
      lastLength = lastLength/haystack.GetLength(rank); 
      var value = last/lastLength; 
      last -= value * lastLength; 

      var index = value + haystack.GetLowerBound(rank); 
      if (index > haystack.GetUpperBound(rank)) 
       throw new IndexOutOfRangeException(); 
      indexes[rank] = index; 
     } 

     return indexes; 
    } 
} 
+0

這很乾淨,但ToList'調用讓我覺得有點懶......爲什麼要將多維數組的全部內容複製到'List '只能使用'IndexOf'?你可以編寫自己的枚舉枚舉數組。 – 2010-07-16 01:29:24

+0

好點。無論如何,我正在考慮增加對範圍邊界的支持,因爲我會改變這一點。 – 2010-07-16 01:33:08