将多维数组反转4次

时间:2015-04-29 11:02:19

标签: c# arrays multidimensional-array

对于一个简单的游戏,我需要一个在启动时动态生成的记分板。该记分板在C#中存储为多维数组。生成基本分数并不难,但问题是该数组应该反转4次,如下所示。

多维数组:

int[,] scoreBoard = new int[4, 4];

基数:

    {
      5,  10,  15,  20
     10,  15,  20,  25
     15,  20,  25,  30
    }

应该成为:

    {
      5,  10,  15,  20,  20,  15,  10,   5
     10,  15,  20,  25,  25,  20,  15,  10
     15,  20,  25,  30,  30,  25,  20,  15
     15,  20,  25,  30,  30,  25,  20,  15
     10,  15,  20,  25,  25,  20,  15,  10
      5,  10,  15,  20,  20,  15,  10,   5
}

1 个答案:

答案 0 :(得分:2)

var result = ArrayReflection(scoreBoard);       

public static T[,] ArrayReflection<T>(T[,] arr)
{
    // number of rows in array
    int m = arr.GetLength(0);
    // number of columns in array
    int n = arr.GetLength(1);
    var res = new T[m*2, n*2];

    for(int r=0; r<m; r++)
        for(int c=0; c<n; c++)
    {
        res[r,c] = arr[r,c];
        res[r,n + c] = arr[r, n - c - 1];
        res[r + m,c] = arr[m - r - 1, c];
        res[r+m,n+c] = arr[m - r - 1, n - c - 1];   
    }

    return res;     
}