如何让这个二维数组向右旋转 90 度? [英] How do I get this 2D Array to rotate to the right 90 degrees?
本文介绍了如何让这个二维数组向右旋转 90 度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我有一个二维数组,它应该向右旋转 90 度,但它向左旋转.实在想不通为什么
So I have a 2D array, and it is supposed to rotate to the right 90 degrees, but instead it rotates to the left. Really can't figure out why
公共类 CrackCode16 {
public class CrackCode16 {
public static void main (String args[]){
int [] [] oldarray = new int [3][3];
int value = 1;
for (int i = 0; i < 3; i++){
for (int j =0; j<3; j++){
oldarray[i][j] = value;
value++;
}
}
for (int i = 0; i < 3; i++){
for (int j =0; j<3; j++){
System.out.print(oldarray[i][j] + " ");
}
System.out.println("");
}
oldarray = rotate(oldarray, 3);
System.out.println("");
for (int i = 0; i < 3; i++){
for (int j =0; j<3; j++){
System.out.print(oldarray[i][j] + " ");
}
System.out.println("");
}
}
public static int [][] rotate (int [][] passedIn, int n){
int [][] newarray = new int [n][n];
for (int i = 0; i < n; i++){
for (int j =0; j<n; j++){
newarray[i][j] = passedIn [j][n-1-i];
}
}
return newarray;
}
}
输出:
1 2 3
4 5 6
7 8 9
1 2 3
4 5 6
7 8 9
3 6 9
2 5 8
1 4 7
3 6 9
2 5 8
1 4 7
推荐答案
newArray[i][j] = passedIn [n-1-j][i];
代替
newarray[i][j] = passedIn [j][n-1-i];
此外,在使用 Java8 时,您可能会考虑使用 Stream
来打印您的数组:
Additionally, when working with Java8, you might consider using a Stream
to print your array:
Stream.of(oldarray).forEach(e -> System.out.println(Arrays.toString(e)));
这篇关于如何让这个二维数组向右旋转 90 度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文