Monday, August 10, 2009

Rotating a 2-D array

Not as easy as you would think:





public static Object[,] rotateClockWise(Object[,] inArray)
{
int width = inArray.GetLength(1);
int height = inArray.GetLength(0);
Object[,] outArray = new Object[width, height];

for (int i = 0; i < width; i++)
{
for (int j = 0; j < height; j++)
{
outArray[i, j] = inArray[height - 1 - j, i];
}
}

return outArray;
}

public static Object[,] rotateCounterClockWise(Object[,] inArray)
{
int width = inArray.GetLength(1);
int height = inArray.GetLength(0);
Object[,] outArray = new Object[width, height];

for (int i = 0; i < width; i++)
{
for (int j = 0; j < height; j++)
{
outArray[i, j] = inArray[j, width - 1 - i];
}
}

return outArray;
}



No comments:

Post a Comment