I'm supposed to write a method that creates a 2d matrix from an array, for instance: ({1, 2, 3, 4}, 3) should return the matrix {{1, 2, 3}, {4}}
public class Matrix {
public static int[][]toM(int[] array, int a) {
int[][]matrix = new int [(array.length + a- 1)/ a][a];
for (int i = 0; i < array.length; i++){
int value = array[i];
value = value++;
for (int row = 0; row < (array.length + a- 1)/a; row++) {
for (int col = 0; col < a; col++) {
matrix[row][col]= value++;
}
}
}
return matrix;
}
}
a is the number of elements in each row. how am i supposed to get [[1, 2, 3], [4]] if my input is int[] array = {1,2,3,4} and int n =3? I'm getting [[4, 5, 6], [7, 8, 9]]?