How to rotate a two dimensional array by 90 degrees clockwise or counter clockwise like Knightfall game

I was playing an old game called Knightfall when something came to my mind… ok, you can rotate the Display Object and this is easy, but how can you rotate the two dimensional array which is obviously storing game field information?

I mean some function which will turn an array like this:

into this one:

It seems an easy task but it’s not… and around the web you can only find examples building a new array, but I wanted to transform the array itself.

So I am sharing you these two functions to rotate by 90 degrees clockwise and counter clockwise any two dimensional array with the same number of rows and columns.

Enjoy it, as you won’t find a lot about this topic around the web.

And this is the result: first, the original array, then the same array rotated clockwise, and last the rotated array rotated again, counter clockwise, to give us the original array.

Hope you will find it useful, what about a rotating Bejeweled game?

  • I am sure I could work this out in time, but I am glad I won’t have to now :D Thanks!

  • Christian Scholz-Flöter

    Do italian clocks work differently from others? I’d call that second array a counter-clockwise rotated version of the original, but then, I am no mathematician/geek/italian programmer ;-)

  • Great little tutorial, I’d love to get into game designing at some point soon. :)

  • I solved this problem some time ago here -http://www.kirupa.com/forum/showthread.php?327814-2D-Array-Transformations

    I see that you are trying to go about editing the array in place, which is interesting, but the code has quite a bit more maths going on, and it doesn’t look it support rotating non-square grids. For example, rotating a 4×3 grid should produce a 3×4 grid.

    Tricky stuff, thanks for sharing :)

  • kristian welsh

    this will be very useful in an upcoming game i am creating as a project for my college. Thank you!

  • Hi
    This trick can be used in mathematical applications.
    Thank you :-)

  • Hi,
    Liked your solution and explanation. Here is my solution for in-place rotation – http://k2code.blogspot.in/2014/03/rotate-n-n-matrix-by-90-degrees.html. I tried to come up with diagrams, was not understanding the solution at all.

  • hammad

    write a program 2d array find in degree and out degree in c++