Ovviamente solo una bozza migliorabile:
codice:
public class Matrix {
private String[][] matrix = null;
public Matrix() {
}
public Matrix(String[][] matrix) {
this.matrix = matrix;
}
public Matrix getSubMatrix(int row, int column, int width, int height) {
try {
int r0 = matrix.length - row > height ? height : matrix.length - row;
int c0 = matrix.length - column > width ? width : matrix.length - column;
String[][] m = new String[r0][c0];
for (int r = 0; r < m.length; r++) {
for (int c = 0; c < m[0].length; c++) {
m[r][c] = matrix[row + r][column + c];
}
}
return new Matrix(m);
} catch (Exception e) {
return new Matrix();
}
}
public String getValue(int row, int column) {
try {
return matrix[row][column];
} catch (Exception e) {
return "";
}
}
public void setValue(int row, int column, String value) {
try {
matrix[row][column] = value;
} catch (Exception e) {
}
}
public int getRows() {
try {
return matrix.length;
} catch (Exception e) {
return 0;
}
}
public int getColumns() {
try {
return matrix[0].length;
} catch (Exception e) {
return 0;
}
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer("");
try {
for (int r = 0; r < matrix.length; r++) {
sb.append("[");
for (int c = 0; c < matrix[0].length; c++) {
sb.append("[" + matrix[r][c] + "]");
}
sb.append("]");
}
} catch (Exception e) {
sb.append("[]");
}
return sb.toString();
}
public static void main(String[] args) {
String[][] matrix = {
{"00", "01", "02", "03", "04"},
{"10", "11", "12", "13", "14"},
{"20", "21", "22", "23", "24"},
{"30", "31", "32", "33", "34"},
{"40", "41", "42", "43", "44"}
};
Matrix m = new Matrix(matrix);
int n = 2;
int rLimit = (int) Math.ceil((double) m.getRows() / (double) n);
int cLimit = (int) Math.ceil((double) m.getColumns() / (double) n);
for (int r = 0, rr = 0; r < rLimit; r++, rr += n) {
for (int c = 0, cc = 0; c < cLimit; c++, cc += n) {
Matrix sm = m.getSubMatrix(rr, cc, n, n);
System.out.println(sm);
}
}
}
}