java - Creating a matrix out of a given vector -


i'm having trouble splitting vector 2d matrix or given side. example, given vector {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}, rows (3), , columns (4) can turned {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}.

as of right now, code prints out entire vector in array many rows are.

int[][] reshape(int[] vector, int row, int col) {         if (!isreshapable(vector.length, row, col)) {             return null;         } else {             int[][] matrix = new int[row][col];             (int = 0; < row; i++) {                 (int j = 0; j < col; j++) {                     arrays.fill(matrix, vector);                 }             }             return matrix;         }     }     

you're iterating both i , j. use them (and position in vector) like,

int p = 0; int[][] matrix = new int[row][col]; (int = 0; < row; i++) {     (int j = 0; j < col; j++, p++) {         matrix[i][j] = vector[p];     } } 

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -