gpt4 book ai didi

java - 如何在java中切片或复制矩阵的中心部分

转载 作者:行者123 更新时间:2023-12-02 09:04:59 25 4
gpt4 key购买 nike

void CropCenterPart (int a[][],int rows,int cols) → 该函数应该提取中心部分并从 arr 中打印,中心部分包​​括除边界之外的所有内容(边界包括第一行,第一列、最后一行和最后一列)。

注意:main函数中创建了一个矩阵。我必须通过传递签名来使用这个函数

原始矩阵

1 2 3 4
6 7 8 9
1 1 1 1
6 7 8 9

带中心的矩阵。

7 8
1 1

我还使用了 Arrays.copyofRange(array,start,end) 但它给了我 null 或地址,不会打印任何内容。

附上一些代码

   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("");
}

最佳答案

如果维度小于3,则那里没有中间矩阵,尝试使用代码,

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;
}

在主函数(或您调用的任何函数)中,像这样打印

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]);
}
}

关于java - 如何在java中切片或复制矩阵的中心部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59892635/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com