顺时针旋转阵列

时间:2010-11-04 21:47:42

标签: c# arrays math

让我们从一个简单的16 x 16整数阵列开始 如何以90度顺时针顺序将'SomeValue'插入数组中。

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

结果应该类似于下面的旋转数组。

  

正常顺序:
  0,1,2,
  3,4,5,
   6,7,8,

     

顺时针旋转:
  6,3,0,
  7,4,1,
  8,5,2,

3 个答案:

答案 0 :(得分:6)

你在找这样的东西吗?

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

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

答案 1 :(得分:2)

按照@Albin Sunnanbos的建议并使用二维数组。然后看看this related question

答案 2 :(得分:1)

如果你想生成旋转的数组,你可以这样做

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