我正在写一个带有2个参数,一个int矩阵和1个int数组的方法。该方法必须返回b []数组中具有倍数的a [] []元素之和。
这是方法代码
public static int sum(int[][] a, int[] b) {
int matrixSum = 0;
if (a != null && b != null) {
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a.length; j++) {
boolean multiple = false;
boolean nullRow = false;
if (a[i] == null || a[i].length < 1) {
nullRow= true;
} else {
for (int k = 0; k < b.length && !multiple; k++) {
if (b[k] % a[i][j] == 0) {
matrixSum += a[i][j];
multiple = true;
}
}
}
}
}
}
return matrixSum;
}
这是测试班
public static void main(String[] args) {
int[][] a = {{2, 3, 1}, {1, 1, 1}, {2, 2, 2}};
int[][] a1 = {{2, 3}, {1, 1, 1}, {2, 2, 2}};
int[][] a2 = {{2, 3, 4}, {1, 1}, {2, 2, 2}};
int[][] a3 = {{2, 3, 4}, {1, 2, 3}, {1, 1}};
int[] b = {7, 8, 7, 20};
System.out.println(sum(a, b)); // 15
System.out.println(sum(a1, b)); // 11
System.out.println(sum(a2, b)); // 14
System.out.println(sum(a3, b)); // 11
}
在某些情况下它不能工作,在某些情况下结果不正确,而另一些时候我收到出站错误
答案 0 :(得分:0)
答案 1 :(得分:0)
此代码有效,谢谢
public static int sum(int[][] a, int[] b) {
int matrixSum = 0;
if (a != null && b != null) {
for (int i = 0; i < a.length; i++) {
if (a[i] == null) {
boolean nullRow = true;
} else {
for (int j = 0; j < a[i].length; j++) {
boolean multiple = false;
for (int k = 0; k < b.length && !multiple; k++) {
if (b[k] % a[i][j] == 0) {
matrixSum += a[i][j];
multiple = true;
}
}
}
}
}
}
return matrixSum;
}
答案 2 :(得分:0)
尝试一下:
public static int sum(int[][] a, int[] b) {
if (a == null || b== null) return 0;
int matrixSum = 0;
for (int i = 0; i < a.length; i++) {
if(a[i] == null || a[i].length <1 ) continue;
for (int j = 0; j < a[i].length; j++) {
for (int k = 0; k < b.length ; k++) {
if (b[k] % a[i][j] == 0) {
matrixSum += a[i][j];
break;
}
}
}
}
return matrixSum;
}
使用Stream可以使其更简单,更简洁:
public static int sum(int[][] a, int[] b) {
return Stream.of(a).flatMapToInt( row -> IntStream.of(row)).
filter(i->isMultipleOf(i,b)).sum();
}
private static boolean isMultipleOf(int i, int[] b) {
for(int j : b){
if(j%i == 0) return true;
}
return false;
}