问题描述
我有4个2×2阵列的列表。我希望将它们存储在更大的4×4数组中。前两个数组组成“第一行”,后两个数组组成“第二行”。
代码
static void Test(){
int[,] arr1 = {
{0,1},{2,3}
};
int[,] arr2 = {
{4,5},{6,7}
};
int[,] arr3 = {
{8,9},{10,11}
};
int[,] arr4 = {
{12,13},{14,15}
};
List<int[,]> arrList = new List<int[,]>();
int[,] result = new int[4,4];
arrList.Add(arr1);
arrList.Add(arr2);
arrList.Add(arr3);
arrList.Add(arr4);
int v = 0;
foreach(int[,] x in arrList){
for(int i = 0; i < 2; i++){
for(int j = 0; j < 2; j++){
result[v*i-1,v*j-1] = x[i,j]; //This needs to change
}
}
v += 1;
}
}
基于此示例的最终目标应该是
0 1 4 5
2 3 6 7
8 9 12 13
10 11 14 15
解决方法
最终我使用了以下功能。该函数的作用是将2 x 2或3 x 3的数组循环,并将它们组合为更大的n x n数组。
private static string[,] Combine(List<string[,]> arrList){
int elements = arrList.Count * arrList[0].Length;
int n = (int) Math.Pow((double) elements,0.5);
string[,] result = new string[n,n];
int k = 0;
int r = 0;
int by = 0;
int amt = 0;
if(arrList[0].Length % 2 == 0){
by = (int) Math.Pow(arrList[0].Length,0.5);
amt = n/by;
}else if(arrList[0].Length % 3 == 0){
by = (int) Math.Pow(arrList[0].Length,0.5);
amt = n/by;
}
for(int v = 0; v < arrList.Count; v++){
if(v%amt == 0 && v != 0){
k=0;
r +=1;
}
for(int i = 0; i < by; i++){
for(int j = 0; j < by; j++){
result[r*by+i,k*by+j] = arrList[v][i,j];
}
}
k+=1;
}
return result;
}