Doubling a Matrix

前端 未结 3 749
后悔当初
后悔当初 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:33

    I'm no sure if that is what you are looking for but try this:

    for (int i = 0; i < newMatrix.length; i++) {
        for (int j = 0; j < newMatrix.length; j++) {
            newMatrix[i][j] = matrix[i/size][j/size];
        }
    }
    

    Note: This code is surely not the best solution but a fast an easy one. It only works if both dimensions are the same size and it won't work if newMatrix is not exactly two times matrix. If it's always just to "double" a matrix it should work fine.


    Output:
    If you choose size 2 than it will output:

    Enter the size of the matrix
    2
    The Matrix is
    3 5 
    5 2 
    The newMatrix is
    3 3 5 5 
    3 3 5 5 
    5 5 2 2 
    5 5 2 2 
    

    and for size 3 it would be for example

    Enter the size of the matrix
    3
    The Matrix is
    4 4 3
    5 9 4
    7 4 1
    The newMatrix is
    4 4 4 4 3 3
    4 4 4 4 3 3
    5 5 9 9 4 4
    5 5 9 9 4 4
    7 7 4 4 1 1
    7 7 4 4 1 1
    

    It's not clear what you are asking but I hope this helps (:

提交回复
热议问题