顺时针旋转数组

3
让我们从一个简单的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,

1
你的代码无法编译,z未声明。你还应该简化生活,使用二维数组,如 int[,] image = new int[16, 16]; - Albin Sunnanbo
“z”是什么?你想要旋转矩阵还是向其中插入数值?这是两个不同的事情。 - Pedro Silva
哎呀,把 z 改成了 y,哈哈,是我的错 ;) - Jeremi Stadler
现在它已经编译通过了,你期望代码会做什么?生成“顺时针旋转”的数组吗? - Albin Sunnanbo
我想以一种方式将'SomeValue'插入图像数组中,使图像顺时针旋转90度。 - Jeremi Stadler
3个回答

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
那么矩形数组呢?如果我们需要旋转一个[52]的数组,而不是[1616]呢? - lvictorino
对于矩形: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];}}}。请注意,在“copy”数组中,现在假定宽度变为高度,反之亦然。 - Marcin

2

你知道如何逆时针旋转它吗? - Jeremi Stadler
我的对称感告诉我要使用[3-j,i]而不是[j,3-i]。在你的情况下,它是15而不是3。 - Dialecticus

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

它输出为二维数组,但我可以轻松转换它 :D - Jeremi Stadler
1
二维数组不是一个 bug,它是一种特性 :-) (它提高了代码的可读性和意图) - Albin Sunnanbo
你说得对!二维数组 actual 让它更容易了 :D - Jeremi Stadler

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接