Rotate an array clockwise

Let's start with a simple array x 16 x 16.
How to insert “SomeValue” into the array in 90 degree clockwise order.

int[] image = new int[16 * 16];

for (int x = 0; x < 16; x++)
{
    for (int y = 0; y < 16; y++)
    {
        int someValue = x * y;

        // This is the line I think is wrong
        image[x + (y * 16)] = someValue; 
    }
}

The result should look like a Rotating Array below.

Normal order:
0, 1, 2,
3, 4, 5,
 6, 7, 8,

Clockwise rotation:
6, 3, 0,
7, 4, 1,
8, 5, 2,

+3
source share
3 answers

Are you looking for something like this?

0 0 0 1 1 1 2 2 2   x
0 1 2 0 1 2 0 1 2   y
= = = = = = = = =
6 3 0 7 4 1 8 5 2   m*(m-1-y)+x

for m = 3.


const int m = 16;
int[] image = new int[m * m];

for (int x = 0; x < m; x++)
{
    for (int y = 0; y < m; y++)
    {
        int someValue = x * y;

        image[m*(m-1-y)+x] = someValue; 
    }
}
+6
source

Follow the recommendations of @Albin Sunnanbos and use a two-dimensional array. Then look at this related question .

+2

, :

int[,] image = new int[16 , 16];

int current = 0;
for (int x = 15; x >= 0; x--)
{
    for (int y = 0; y < 16; y++)
    {
        image[x, y] = current;
        current++;
    }
}

// Output

for (int y = 0; y < 16; y++)
{
    for (int x = 0; x < 16; x++)
    {
        Console.Write(image[x,y] + ", ");
    }
    Console.WriteLine();
}
+1

Source: https://habr.com/ru/post/1773144/


All Articles