views:

275

answers:

7

Possible Duplicate:
How do you rotate a two dimensional array?

I have 32 Int32's. Picture this as a block of 32 * 32 bits.

I need to rotate this block of bits 90 degrees clockwise. What's the most efficient way to do this in C#?

+2  A: 
int[] oldArray;
int[] newArray;

for(int i = 0; i < 32; i++)
{
   for(int j = 0; j < 32; j++)
   {
      newArray[i] += ((oldArray[j] & (1 << i)) >> i) << j;
   }
}

This is written off the top of my head, but it should work.

Hannesh
`<code>` doesn't work in Markdown - indent by 4 spaces or highlight the code and use the code icon or Ctrl+K
ChrisF
Thanks, I updated it.
Hannesh
Thanks @Hannesh. Yes, this will work. Out of interest, the += could be optimized to |=, which is slightly faster I believe.I was wondering if there is some fancy formula to do this is less that 32 * 32 ops, but I think what you have written is as lean as it will ever get :)
IanC
Using |= may well be faster, but it definitly won't be slower. You may be able to do it with less assigments by splitting it up and rotating the sub-blocks, like Dysaster said in your comments.
Hannesh
+2  A: 

Rotate which way by 90 degrees? This rotates anticlockwise:

static uint[] BitwiseRotateAnticlockwise(uint[] matrix)
{
    uint[] output = new uint[matrix.Length];
    uint mask = 0x01;
    for (int i = 0; i < output.Length; ++i)
    {
        for (int j = 0; j < matrix.Length; ++j)
        {
            output[i] <<= 1;
            output[i] += (matrix[j] & mask) > 0 ? 1U : 0U;
        }
        mask <<= 1;
    }
    return output;
}
Richard Cook
A: 

Thanks @Dimitry

I figured out a better way of solving the problem, using DeBruijn LSB lookups, rather than rotating.

IanC
Can you elaborate on the solution you've found? Or maybe provide a link?
Dysaster
A: 

@Mikael Svenson you answered this, but as a comment.

IanC
You commented on this, but as an answer. ;)
David Brown
A: 

This can be solved in O(1), you must only save information about how much degrees was your matrix rotated, and overload matrix reading functions, get into it other matrix traversing algorithm depends on how much degrees matrix was rotated.

Svisstack
A: 

If you need super efficient solution you can use a data-structure solution, a new

class Rotatable{
    bool IsRotated;
    array myarray;

    object get(int idx1,int idx2)
    {
        if(IsRotated)
              return myarray.getElementAt(calcRotatedIdx1(idx1,idx2),calcRotatedIdx2(idx1,idx2);

        return myarray.getElementAt(idx1,idx2);
    }

}

it has very slight performance overhead when accessing the new array but will get you there very fast

Ahmed Khalaf