逐层旋转二维数组

时间:2019-06-07 15:54:03

标签: java arrays

问题是;用户输入2个输入以创建二维数组,即行和列。 然后2D数组填充随机数。在该用户输入另外1个输入后,该输入将旋转数组多少次。这是我的问题,我不知道如何逐层旋转数字。

Photo of Rotation

import java.util.Random;
import java.util.Scanner;

public class RandomArray
{
public static void main(String args[]){

    System.out.print("Enter number of row: ");
    Scanner sc=new Scanner(System.in);
    int rows=sc.nextInt();
    System.out.print("Enter number of column : ");
    int columns=sc.nextInt();     

    int twoD[][]=new int[rows][columns];

    for(int i = 0; i < rows; i++){
        for(int j = 0; j < columns; j++){
            twoD[i][j] =  (int) (Math.random()* 10) ;
        }
    }

    for(int k = 0; k < rows; k++){
        for(int l = 0; l < columns; l++){
            System.out.print(twoD[k][l] + " ");
        }

        System.out.println();
    }
   }
}


//For example:

//  Enter number of row: 4
//  Enter number of column: 4
//  It will print:
//  2 9 6 3
//  2 1 4 2
//  4 1 0 1
//  7 4 2 8

//If user enter 3 as a rotation number.It should be like this:
//  3 2 1 8
//  6 1 1 2
//  9 0 4 4
//  2 2 4 7

1 个答案:

答案 0 :(得分:1)

假设您要顺时针旋转它。您可以创建另一个2d数组rotated(以临时存储旋转后的值)。然后,您遍历每行r和列c

for (int r = 0; r < rows; r++) {
    for (int c = 0; c < columns; c++) {
        rotated[c][columns - 1 - r] = twoD[r][c]
    }
}

twoD = rotated

您可以将其循环显示转数。