3

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,

Jeremi Stadler
  • 2,567
  • 4
  • 21
  • 22

3 Answers3

6

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; 
    }
}
dtb
  • 213,145
  • 36
  • 401
  • 431
  • 1
    And what about rectangle arrays? what if instead of [16*16] we need to rotate a [5*2] array ? – lvictorino Feb 25 '14 at 09:37
  • For rectangles: `int[] copy = new int[source.Length]; int i = 0; for(int x=0; x < width; x++) { for(int y=height-1; y >= 0; y--) {copy[i++] = source[y * width + x];}}`. Note that you now assume width becomes height and vice versa in the "copy" array – Marcin Oct 24 '17 at 23:54
2

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

Community
  • 1
  • 1
Anders Fjeldstad
  • 10,724
  • 2
  • 33
  • 50
1

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();
}
Albin Sunnanbo
  • 46,430
  • 8
  • 69
  • 108