如何在二维数组C#中垂直翻转整数



我试图垂直翻转一个2D阵列,所以我试图打开这个:

1 2 3 4 1
5 6 7 8 2 
4 3 2 1 1
8 7 6 5 2

进入

8 7 6 5 2
4 3 2 1 1
5 6 7 8 2
1 2 3 4 1

到目前为止,我有一个嵌套的for循环,

for (int i= 0; i<rows; i++)
{
for (int j = 0; j<columns; j++)
{
WillSmith[i, j] = arr[i,j];

}
}

"WillSmith"是翻转阵列,但当我返回时,我一直得到相同的数组。

我不知道我做错了什么

编辑:我现在把它换成了arr[j,I],但现在我得到一个错误,说我已经溢出了索引。我需要这一点才能用于非方形数组,而且由于我测试的数组不是方形的,所以我不能只使用newArray[I,j]=oldArray[j,I]。

WillSmith[rows-1-i, j] = arr[i, j];

您希望保留列索引,只需按列反转行即可。所以从头读,从头写。

实现这一点的最快方法,对于任何类型的数组,都是根据需要使用Buffer.BlockCopy()交换行。

class Program
{
static void Main(string[] args)
{
var test = new int[,] {
{1, 2, 3, 4, 1 },
{5, 6, 7, 8, 2 },
{4, 3, 2, 1, 1 },
{8, 7, 6, 5, 2 } };
var res = ReverseRows(test);
Console.WriteLine();
PrintArray(test);
Console.WriteLine();
PrintArray(res);
}
public static void PrintArray<T>(T[,] array, int colWidth=9)
{
int n = array.GetLength(0), m = array.GetLength(1);
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
Console.Write(array[i,j].ToString().PadLeft(colWidth));
}
Console.WriteLine();
}
}
public static T[,] ReverseRows<T>(T[,] array)
{
int n = array.GetLength(0), m = array.GetLength(1);
T[,] result = array.Clone() as T[,];
for (int i = 0; i < n/2; i++)
{
SwapRows(result, i, n - i - 1); 
}
return result;
}
static void SwapRows<T>(T[,] array, int row1, int row2)
{
if (row1 == row2) return;
int n = array.GetLength(0), m = array.GetLength(1);
int byteLen = Buffer.ByteLength(array) / (n * m);
T[] buffer = new T[m];
// copy row1 to buffer
Buffer.BlockCopy(array, row1 * m * byteLen, buffer, 0, m * byteLen);
// copy row2 to row1
Buffer.BlockCopy(array, row2 * m * byteLen, array, row1 * m * byteLen, m * byteLen);
// copy buffer to row2
Buffer.BlockCopy(buffer, 0, array, row2 * m * byteLen, m * byteLen);
}
}

垂直反转80*260阵列的最快方法示例

const int ROW = 80;
const int COL = 260;
public ushort[,] FlipFrameVertical(ushort[,] frame)
{
// ushort size is 2 bytes
int byteSize = 2 * COL;
ushort[,] frame_flipped = new ushort[ROW, COL];
for (int i = 0; i < ROW; i++)
{
Buffer.BlockCopy(frame, (byteSize * (ROW-1-i)), frame_flipped, 
byteSize * i, byteSize);
}
return frame_flipped;
}

根据数据类型更改字节大小。

最新更新