gpt4 book ai didi

java - 将数组再旋转 2 次?

转载 作者:行者123 更新时间:2023-11-30 08:06:44 25 4
gpt4 key购买 nike

我已经能够通过反转坐标数组来旋转它,但我需要其他 2 个可能的旋转,并且不知道该怎么做。这是我当前的代码,我打印坐标作为示例。

/**
* Visual representation of coords.
*
* xxxxx
* xxxxx
* xx+xx
* xxxxx
* xxxxx
*
* + is [0,0]
*/

public static void main(String[] args) {
List < String > array = getCoordinates(0, 0, 2);

int i = 0;

System.out.println("Rotation 1: ");

for (String line: array) {
if (i == 4) {
System.out.println(line);
i = -1;
} else {
System.out.print(line + " ");
}
i++;
}

System.out.println(" ");
System.out.println("Rotation 2: ");

Collections.reverse(array);
i = 0;

for (String line: array) {
if (i == 4) {
System.out.println(line);
i = -1;
} else {
System.out.print(line + " ");
}
i++;
}

}

这是 getCoordinates 方法。

public static List < String > getCoordinates(int x, int z, int range) {

List < String > ids = new ArrayList < String > ();

for (int i = -range; i <= range; i++) {
for (int j = -range; j <= range; j++) {
int nx = x + i;
int nz = z + j;
ids.add("[" + nx + "," + nz + "]");
}
}

return ids;
}

我对大量代码感到抱歉,但这是我能够最好地说明我正在尝试的内容的唯一方法。

编辑这是输出。

Rotation 1: 
[-2,-2] [-2,-1] [-2,0] [-2,1] [-2,2]
[-1,-2] [-1,-1] [-1,0] [-1,1] [-1,2]
[0,-2] [0,-1] [0,0] [0,1] [0,2]
[1,-2] [1,-1] [1,0] [1,1] [1,2]
[2,-2] [2,-1] [2,0] [2,1] [2,2]

Rotation 2:
[2,2] [2,1] [2,0] [2,-1] [2,-2]
[1,2] [1,1] [1,0] [1,-1] [1,-2]
[0,2] [0,1] [0,0] [0,-1] [0,-2]
[-1,2] [-1,1] [-1,0] [-1,-1] [-1,-2]
[-2,2] [-2,1] [-2,0] [-2,-1] [-2,-2]

由于它是正方形,因此这里还有另外两种可能的旋转。这些就是我想要得到的。

Here is a relevant image i found on the web, showing 3 rotations of a square grid.

enter image description here .

最佳答案

这是轮换的逻辑。尝试自己编写代码...

将原图向右旋转 90 度:

/**
* original
* wqxxx
* asxxx
* xx+xx
* xxxxx
* xxxxx
*
* rotated
* xxxaw
* xxxsq
* xx+xx
* xxxxx
* xxxxx
*/

// w: -2,-2 -> -2,2
// q: -2,-1 -> -1,2
// a: -1,-2 -> -2,1
// s: -1,-1 -> -1,1

右旋逻辑:旋转后的行=原始列,旋转后的列=原始行*-1

向左旋转原图 90 度:

/**
* original
* wqxxx
* asxxx
* xx+xx
* xxxxx
* xxxxx
*
* rotated
* xxxxx
* xxxxx
* xx+xx
* qsxxx
* waxxx
*/

// w: -2,-2 -> 2,-2
// q: -2,-1 -> 1,-2
// a: -1,-2 -> 2,-1
// s: -1,-1 -> 1,-1

左旋转逻辑:旋转后的行=原始列*-1,旋转后的列=原始行

关于java - 将数组再旋转 2 次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30997992/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com