Finding position of an element in a two-dimensional array?

zeta picture zeta · Jul 16, 2010 · Viewed 40.5k times · Source

Well simple question here (maybe not a simple answer?)

Say I have a two dimensional array

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

Now suppose I want to get the position of the number 6

I know with a one-dimensional array i can use Array.indexOf() but what would my options be with 2-dimensional arrays?

Thanks!

Answer

Dan Tao picture Dan Tao · Jul 16, 2010

I'd say something like this:

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