在一个函数中,我有两个 2D 数组(超过 50x50),它们具有相同的列数但行数不同。基本上我需要从 0 到 2 范围内删除包含数字的公共列
例:
A: 3 0 0 0 0 1 0
5 0 0 6 0 0 2
2 0 0 7 1 0 0
B: 2 3 0 1 0 0 1
4 9 0 2 0 0 0
在这种情况下,我必须删除第 3、6 和 7 列(到 A 和 B),因为第 3 列只有 0,第 6 列只有 0 和 1,最后一列都是从 0 到 2 的 Nr。
我可以使用像LinearAlgebra.deleteColumns(A,2,5,6)这样的函数;和LinearAlgebra.deleteColumns(B,2,5,6);但是由于我的输入数组很大,我必须做一个列解析来比较两个数组。
有什么想法可以解决这个问题吗?这是使用 3 for loops(java) 的原始想法
for(int col=0; col < A[0].length; col++){ // step through each column
int cnt = 0;
for(int row = 0; row < B.length ; row ++){
if(!(B[col][row].equals(0 | 1 | 2))) {
cnt++;
}
}
if(cnt == 0) {
// store number of column -> use later on LinearAlgebra.deleteColumns
}
for(int row = 0; row < A.length ; row++){
if(!(A[col][row].equals(0 | 1 | 2)))
cnt++;
}
if(cnt == 0){
// check aswell all values of B otherwise iterate next column
}
}
boolean result[] = new boolean[<num of columns>];
for (int i = 0; i < result.length; ++i)
result[i] = true;
for (int row = 0; row < arrayA.length; ++row) {
for (int col = 0; col < arrayA[row].length; ++col)
result[col] &= arrayA[row][col] == 0;
}
for (int row = 0; row < arrayB.length; ++row) {
for (int col = 0; col < arrayB[row].length; ++col)
result[col] &= arrayB[row][col] == 0;
}
for (int i = 0; i < 6; ++i)
System.out.println(result[i]);
现在,result
数组中的每个单元格(列)将指示两个数组的哪一列都包含零。
注意:*这假设您说的两个数组具有相同的列数
因评论而编辑:
如果要删除其值在某个包含范围内的列,请使用以下条件:
result[col] &= arrayA[row][col] >= minRange && arrayA[row][col] <= maxRange;
对于独家范围,只需删除=
标志
并对第二个数组执行相同的操作
您可能会混淆您的 col 和行顺序,因为您使用 A[0].length
获取行计数,但您在B[col][row]
中使用它,但对于这部分,我让您更详细地了解。
无论如何,如果我很好地理解您的问题,您正在寻找仅包含 0 的列。
为此,您应该首先在 true 处初始化一个bool
,当值不同于 0 时,您将其输入为 false。 对第二个过程使用相同的过程bool
最后比较两个布尔值以了解是否必须删除列;)
创建一个boolean
标志,遍历列并决定要删除哪些列。
查找可删除列的示例:
boolean deleteFlag;
for ( int i = 0; i < columnAmount; i++ ) {
deleteFlag = true;
for (int j = 0; j < firstTableRowAmount; j++ ) {
if (A[j][i] != 0) {
deleteFlag = false;
break;
}
}
if(!deleteFlag) {
continue;
}
for (int j = 0; j < secondTableRowAmount; j++ ) {
if (B[j][i] != 0) {
deleteFlag = false;
break;
}
}
if(deleteFlag) {
callDeleteColumnFunction(i);
}
}
callDeleteColumnFunction(i)
是一个删除两个 2D 数组的i-th
列的函数。
辅助函数:
private boolean isColumnDeletable(final int column, final int[][] array) {
for (int row = 0; row < array.length; row++) {
if (array[row][column] != 0)
return false;
}
return true;
}
用法示例:
int[][] values1 = new int[][] {{1, 1, 1, 0, 1}, {2, 2, 2, 0, 2}, {3, 3, 3, 0, 3}};
int[][] values2 = new int[][] {{4, 4, 4, 0, 4}, {5, 5, 5, 0, 5}};
for (int column = 0; column < values1[0].length; column++) {
System.out.printf("Checking column %d: ", column + 1);
if (isColumnDeletable(column, values1) && isColumnDeletable(column, values2))
System.out.printf("Deletable!n");
else
System.out.printf("Not deletable!n");
}
输出:
Checking column 1: Not deletable!
Checking column 2: Not deletable!
Checking column 3: Not deletable!
Checking column 4: Deletable!
Checking column 5: Not deletable!