Have you ever needed to rotate (or turn) the contents of a 2d array (non-jagged: same width and height)? Well, recently I needed to do just that. A single function makes it possible.
Luckily it's not difficult at all. The rotation is really just a matter of re-arranging the contents of the array. In other words, moving each y dimension from the source array to the x dimension in the destination array.
namespace ConsoleAppRotateArr
{
class Program
{
static void Main(string[] args)
{
// create a shape
uint[,] shape = new uint[3, 3];
shape[0, 0] = 1;
shape[1, 0] = 1;
shape[2, 0] = 1;
shape[0, 1] = 0;
shape[1, 1] = 0;
shape[2, 1] = 1;
shape[0, 2] = 0;
shape[1, 2] = 0;
shape[2, 2] = 0;
// rotate the shape left
shape = Rotate(shape, Rotation.Left);
}
/// <summary>
/// Rotation direction
/// </summary>
enum Rotation
{
/// <summary>
/// Turn left 90 degrees (counter clockwise)
/// </summary>
Left,
/// <summary>
/// Turn right 90 degrees (clockwise)
/// </summary>
Right
}
/// <summary>
/// Rotate a non-jagged, rectangular array
/// </summary>
/// <param name="grid">Non-jagged, rectangular array</param>
/// <param name="rotate">Rotation direction enum</param>
/// <returns>Non-jagged, rectangular array</returns>
static uint[,] Rotate(uint[,] grid, Rotation rotate)
{
// get array dimensions
uint xl = (uint)grid.GetLength(0);
uint yl = (uint)grid.GetLength(1);
// only rotate non-jagged, rectangular array
if (xl.Equals(yl))
{
uint[,] temp = new uint[xl, yl];
for (int y = 0; y < yl; y++)
for (int x = 0; x < xl; x++)
if (rotate.Equals(Rotation.Right))
temp[yl - y - 1, x] = grid[x, y];
else
temp[y, xl - x - 1] = grid[x, y];
return temp;
}
else
return grid;
}
}
}
The approach is probably not suitable for very large arrays. This method however, was perfect for the small arrays, such as a tetris block. ;)
Like always, I would appreciate comments or suggestions on the code.
Environment:
Microsoft ® Visual Studio 2008
Microsoft ® .NET framework 3.5
Microsoft ® Windows XP (SP2)
0 comments:
Post a Comment