Reputation: 5
void cropCenterPart (int a[][],int rows,int cols)
→ This function should extract center part and print from arr, center part includes everything except Boundaries (Boundaries include 1st row, 1st col, last row and last col).
Note: there is a matrix created in main function. I have to use this function by passing signatures
Original Matrix
1 2 3 4
6 7 8 9
1 1 1 1
6 7 8 9
Matrix with center.
7 8
1 1
I also used Arrays.copyofRange(array,start,end) but its gives me null or address nothing will be printed.
Attach some code
public void cropCenterPart(int a[][],int rows,int cols){
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (i == 0)
System.out.print(a[i][j] + " ");
else if (i == rows - 1)
System.out.print(a[i][j] + " ");
else if (j == 0)
System.out.print(a[i][j] + " ");
else if (j == cols - 1)
System.out.print(a[i][j] + " ");
else
System.out.print(" ");
}
System.out.println("");
}
System.out.println("");
}
Upvotes: 0
Views: 430
Reputation: 5
Answer would be
public class A {
public void extractBoundaries(int a[][],int rows,int cols){
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (i == 0 || j == 0 || i == 3 || j == 3)
System.out.print(a[i][j] + " ");
else
System.out.print(" ");
}
System.out.println("");
}
System.out.println("");
}
public void cropCenterPart(int a[][],int rows,int cols){
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (i == 0 || j == 0 || i == 3 || j == 3)
System.out.print(" ");
else
System.out.print(a[i][j] + " ");
}
System.out.println("");
}
System.out.println("");
}
}
Upvotes: 0
Reputation: 253
If the dimensions are less than 3, there is no middle matrix there, try with code,
private static int[][] cropCenterPart(int[][] arr, int row, int col) {
if (!(row > 2 && col > 2))
return arr;
int[][] resultArr = new int[row - 2][col - 2]; // as the first row,col and
// last row,col is neglected
for (int i = 1; i < row-1; i++) {
System.arraycopy(arr[i], 1, resultArr[i - 1], 0, col - 1 - 1);
}
return resultArr;
}
In main function (or whatever the function you are calling from), print like this
int resultArr[][] = cropCenterPart (arr, row, col);
for(int i = 0; i<row-2; i++) { // here the row is the actual row size of arr
System.out.println();
for(int j=0; j<col-2; j++) {
System.out.print(" " + resultArr[i][j]);
}
}
Upvotes: 1