Jeremi Stadler
Jeremi Stadler

Reputation: 2637

Rotate array clockwise

Lets start out with an simple 16 x 16 array of ints.
How would I insert the 'SomeValue' into the array in a 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 be like the Rotated Array below.

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

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

Upvotes: 3

Views: 3563

Answers (3)

dtb
dtb

Reputation: 217293

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; 
    }
}

Upvotes: 6

Albin Sunnanbo
Albin Sunnanbo

Reputation: 47038

If you want to generate the rotated array you can do like this

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();
}

Upvotes: 1

Anders Fjeldstad
Anders Fjeldstad

Reputation: 10814

Follow @Albin Sunnanbos suggestion and use a two-dimensional array. Then have a look at this related question.

Upvotes: 2

Related Questions