I have a class that rotates a dynamic, squared array. I only require squared rotation. At the moment, it can only rotate to the left. I also need it to rotate to the right.
This answer offered a solution for rotating it counter-clockwise, and my modified version is below for my needs, but I'm lost on how to do the reverse.
Rotate M*N Matrix (90 degrees)
I could call RotateLeft() 3x, but of course, this is inefficient. I'd like to learn of another solution.
My code:
public void RotateLeft()
{
m_array = RotateMatrixCounterClockwise(m_array, m_width, m_height);
}
public void RotateRight()
{
}
public static T[] RotateMatrixCounterClockwise(T[] oldMatrix, int width, int height)
{
T[] newMatrix = new T[width * height];
int newColumn, newRow = 0;
for (int oldColumn = height - 1; oldColumn >= 0; oldColumn--)
{
newColumn = 0;
for (int oldRow = 0; oldRow < width; oldRow++)
{
newMatrix[newRow * width + newColumn] = oldMatrix[oldRow * width + oldColumn];
newColumn++;
}
newRow++;
}
return newMatrix;
}
Solution:
Thanks to Daniel, this code may be useful to others in the future. The only thing that was changed was the inner block:
newMatrix[oldRow * width + oldColumn] = oldMatrix[newRow * width + newColumn];
Full code:
public static T[] RotateMatrixClockwise(T[] oldMatrix, int width, int height)
{
T[] newMatrix = new T[width * height];
int newColumn, newRow = 0;
for (int oldColumn = height - 1; oldColumn >= 0; oldColumn--)
{
newColumn = 0;
for (int oldRow = 0; oldRow < width; oldRow++)
{
newMatrix[oldRow * width + oldColumn] = oldMatrix[newRow * width + newColumn];
newColumn++;
}
newRow++;
}
return newMatrix;
}