How to Rotate a 2D Array of Integers

If they're a 2D array, you can implement rotation by copying with different array access orders.

i.e., for a clockwise rotation, try:

int [,] newArray = new int[4,4];

for (int i=3;i>=0;--i)
{
    for (int j=0;j<4;++j)
    {
         newArray[j,3-i] = array[i,j];
    }
}

Counter-clockwise is similar.


In classic tetris there are very few permutations of objects. I would simply have a constant array for each "tetromino," at each of the 4 positions, and simple logic to choose the appropriate one based on input.

Why waste CPU cycles trying to rotate it?


Don't rotate the pieces with code. Just store an array of the different piece orientations and cycle through them when the piece is rotated. There's no need to dynamically rotate them in a Tetris game.

As the problem domain is Tetris, you will find that a rotation algorithm causes undesirable effects, such as the long thin Tetronimo not alternating between two positions (as it does in the real thing).

Tags:

C#

C++

Arrays

Math