8

这里很简单的问题(也许不是一个简单的答案?)

假设我有一个二维数组

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

现在假设我想得到数字 6 的位置

我知道对于一维数组,我可以使用 Array.indexOf() 但我对二维数组的选择是什么?

谢谢!

4

2 回答 2

20

我会说这样的话:

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);
}
于 2010-07-16T00:04:47.303 回答
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;
    }
}
于 2010-07-16T01:11:57.073 回答