Reputation: 4009
I'm solving an algorithmic task with matrices involved. I need to count each inner square (smaller matrix) inside a larger one. Is there any dependencies between original length and each next? As an example I have this matrix:
1 2 3 4 5 6
7 8 9 10 11 12
13 14 15 16 17 18
19 20 21 22 23 24
25 26 27 28 29 30
31 32 33 34 35 36
As you may see Rows = 6
, Cols = 6
, Length = Rows * Cols;
Problem statement: How to calculate the length of inner matrices:
8 9 10 11
14 15 16 17
20 21 22 23
26 27 28 29
And the last one
15 16
21 22
What I could do:
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
//mirrored row and col e.g. 0 1 2 3 2 1 0
int rowMir = i >= (int)Math.round(M/2.0d) ? (M - 1 - i) : i;
int colMir = j >= (int)Math.round(N/2.0d) ? (N - 1 - j) : j;
int depth = row > col ? col : row; //depth of inner square for each element in iteration. square's border in other words.
//In current matrix there are 3 inner squares (0, 1, 2)
}
}
Is it useful at all? I've tried to calculate it basing on values I've got, but no success until now. Googling gave me nothing in this case.
EDIT
The solution I'm looking for is to get size of the matrix for each element dynamically. Example for value at [i][j]
I've counted the depth
, the inner matrix it belongs to.
Upvotes: 0
Views: 521
Reputation: 9658
In case you actually want to print all the inner matrices and get the count then you can do something like this:
public static void main (String[] args)
{
/* Define Matrix */
int matrixSize = 6;
int[][] matrix = new int[][]{{1, 2, 3, 4, 5, 6 },
{7, 8, 9, 10,11,12},
{13,14,15,16,17,18},
{19,20,21,22,23,24},
{25,26,27,28,29,30},
{31,32,33,34,35,36}};
/* Initialize Count Counter */
int count = 0;
/* Count/Print Inner Matrices */
for(int x = 2; x < matrixSize; x++) {
for(int i = 0; i <= matrixSize - x; i++) {
for(int j = 0; j <= matrixSize - x; j++) {
/* Call Print Matrix Function */
printMatrix(matrix, i, j, x);
++count; /* Increment Counter */
}
}
}
/* Print Actual Count */
System.out.println("\nTotal Inner Square Matrices Count: " + count);
}
/**
* Print Matrix
* Arguments: Matrix, Row Index, Column Index, Matrix Size
**/
public static void printMatrix(int[][] matrix, int i, int j, int size) {
System.out.println();
/* Row Iterator */
for(int iIndex = i; iIndex < i + size; iIndex++) {
System.out.println();
/* Column Iterator */
for(int jIndex = j; jIndex < j + size; jIndex++) {
System.out.print(" " + matrix[iIndex][jIndex]);
}
}
}
Output:
1 2
7 8
2 3
8 9
...
Total Inner Matrices: 54
Upvotes: 0
Reputation: 53839
You can simply decrease by a step of 2
at each iteration:
int minDim = Math.min(rows, columns);
for(int i = minDim ; i >= 0 ; i -= 2) {
System.out.println("Inner length: " + ((rows - i) * (columns - i)))
}
Upvotes: 2