1

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;
}
Noam M
  • 3,156
  • 5
  • 26
  • 41
Bob
  • 115
  • 10
  • Im a bit confused about the use of terminology here. given something like this `int[]{ 11,12, 21, 22, 31, 32, 41, 42, 51, 52 }` what do you expect the outcomes to be in both cases, width = 2, height = 5... if this makes any sense – TheGeneral Apr 04 '18 at 02:19
  • Ok im really confused now, are you working with single dimensional arrays or multidimensional arrays – TheGeneral Apr 04 '18 at 02:23
  • @TheGeneral: He's storing a matrix in a one-dimensional array by just concatenating all the rows. – Daniel McLaury Apr 04 '18 at 03:00

1 Answers1

1

Exchange the roles of oldRow and newRow, and similarly for columns.

Daniel McLaury
  • 4,047
  • 1
  • 15
  • 37