Doubling a Matrix

前端 未结 3 758
后悔当初
后悔当初 2021-01-26 08:21

I\'ve created a two dimensional matrix and populated it with random numbers. I\'ve then printed it out. I need help creating a second matrix that is twice the size of the first,

3条回答
  •  不思量自难忘°
    2021-01-26 08:54

    import java.util.Scanner;
    import java.util.Random;
    
    
    public class MatrixDoubler {
        public static void main(String[] arg) {
            Scanner keyboard = new Scanner(System.in);
            Random rand = new Random();
    
            System.out.println("Enter the size of the matrix");
    
            int size = keyboard.nextInt();
            int A[][] = new int[size][size];
    
            for (int row = 0; row < size; ++row) {
                for (int col = 0; col < size; ++col) {
                    A[row][col] = rand.nextInt(10);
                }
            }
    
            System.out.println("Matrix A:");
            printMatrix(A);
    
            int[][] B = doubleMatrix(A);
    
            System.out.println("Matrix B:");
            printMatrix(B);
        }
    
        private static int[][] doubleMatrix(int[][] A) {
            int rows = A.length;
            assert(rows > 0);
            int cols = A[0].length;
            assert(cols > 0);
    
            int B[][] = new int[rows * 2][cols * 2];
    
            for (int row = 0; row < rows * 2; ++row) {
                for (int col = 0; col < cols * 2; ++col) {
                    B[row][col] = A[row / 2][col / 2];
                }
            }
    
            return B;
        }
    
        private static void printMatrix(int[][] M) {
            for(int i = 0; i < M.length; i++) {
                for(int j = 0; j < M.length; j++) {
                    System.out.print(M[i][j] + " ");
                }
    
                System.out.println();   
            }
        }
    }
    

提交回复
热议问题