I made a method that takes an array and converts it to a matrix, given that it is a valid conversion. However, there is some redundant code in the beginning and I thought maybe you could help me? I am new to programming so avoid complicated imports and such.
private int[][] toMatrix(int[] arr) {
if(validConversion(arr)){
int index = 0;
//redundant
int row = (int) Math.sqrt(arr.length);
int col = (int) Math.sqrt(arr.length);
int[][] matrix = new int[row][col];
for(int i = 0; i<row; i++){
for(int j = 0; j<col; j++){
matrix[i][j] = arr[index];
index++;
}
}
return matrix;
}
return null;
}
boolean validConversion(int[] arr) {
return arr.length == 1 || arr.length % Math.sqrt(arr.length) == 0;
}
toSquareMatrix()
\$\endgroup\$