Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotate 2D Array by 45 degrees

How can I rotate a 2D rectangular array of integers that has odd number of rows by 45 degrees?

So something like

int[] myArray = new int[,]   
{  
    {1, 0 ,1},  
    {0, 1 ,0},  
    {0, 0 ,0},  
} 

into

int[] rotatedArray = new int[,]   
{  
    {0, 1 ,0},  
    {0, 1 ,1},  
    {0, 0 ,0},  
}  

for any dimension (3x3, 5x5, 7x7, etc.).

5x5

0 0 0 0 0  
2 0 0 0 0  
1 1 1 1 1  
0 0 0 0 0  
0 0 0 0 0 

into

1 2 0 0 0  
0 1 0 0 0  
0 0 1 0 0  
0 0 0 1 0  
0 0 0 0 1 

5x5

0 0 0 3 0  
0 0 0 3 0  
0 0 0 3 0  
0 0 0 3 0  
0 0 0 3 0 

into

0 0 0 0 0  
0 0 0 0 3  
0 0 0 3 0  
0 0 3 3 0  
0 3 0 0 0  
like image 919
Kikaimaru Avatar asked Nov 14 '22 09:11

Kikaimaru


1 Answers

This is a code written by me and a friend that solves this:

public static class ArrayExtensions
{
    public static Point RoundIndexToPoint(int index, int radius)
    {
        if (radius == 0)
            return new Point(0, 0);
        Point result = new Point(-radius, -radius);

        while (index < 0) index += radius * 8;
        index = index % (radius * 8);

        int edgeLen = radius * 2;

        if (index < edgeLen)
        {
            result.X += index;
        }
        else if ((index -= edgeLen) < edgeLen)
        {
            result.X = radius;
            result.Y += index;
        }
        else if ((index -= edgeLen) < edgeLen)
        {
            result.X = radius - index;
            result.Y = radius;
        }
        else if ((index -= edgeLen) < edgeLen)
        {
            result.Y = radius - index;
        }

        return result;
    }

    public static T[,] Rotate45<T>(this T[,] array)
    {
        int dim = Math.Max(array.GetLength(0), array.GetLength(0));

        T[,] result = new T[dim, dim];

        Point center = new Point((result.GetLength(0) - 1) / 2, (result.GetLength(1) - 1) / 2);
        Point center2 = new Point((array.GetLength(0) - 1) / 2, (array.GetLength(1) - 1) / 2);
        for (int r = 0; r <= (dim - 1) / 2; r++)
        {
            for (int i = 0; i <= r * 8; i++)
            {
                Point source = RoundIndexToPoint(i, r);
                Point target = RoundIndexToPoint(i + r, r);

                if (!(center2.X + source.X < 0 || center2.Y + source.Y < 0 || center2.X + source.X >= array.GetLength(0) || center2.Y + source.Y >= array.GetLength(1)))
                    result[center.X + target.X, center.Y + target.Y] = array[center2.X + source.X, center2.Y + source.Y];
            }
        }
        return result;
    }     
}
like image 121
Kikaimaru Avatar answered Dec 13 '22 16:12

Kikaimaru