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

前端 未结 2 628
终归单人心
终归单人心 2020-12-07 02:16

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 s

2条回答
  •  北荒
    北荒 (楼主)
    2020-12-07 02:36

    I'd say something like this:

    public static Tuple CoordinatesOf(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);
    }
    

提交回复
热议问题