gpt4 book ai didi

java - 检查二维整数数组中是否存在一行是同一数组中其他两行的总和

转载 作者:行者123 更新时间:2023-12-01 10:52:29 24 4
gpt4 key购买 nike

我试图弄清楚如何编写一个程序,如果二维数组中存在一行是其他两行的总和,则返回 true。

我的程序应该做什么的示例:

如果二维数组是:

2 4 2 3

3 2 6 1

5 6 8 4

9 7 3 7

我的代码应该返回 true,因为 row[2](第三行)是 row[0](第一行)和 row[1](第二行)的总和

在我的代码中,我在二维数组的第一列中搜索,以查找不同行中其他两个值之和的值的位置,但无法弄清楚之后要做什么。

    boolean someRowIsSumOfTwoOthers(int n, int [][] A){ 
int i, j, k;
boolean isTotal = false;
for( i = 0; i < n; i++){
for(j = 0; j < n; j++){
if (i != j){
for( k = 0; k < n; k++){
if ( (i != k) && (j != k) )
if( A[i][0] == A[j][0] + A[k][0] )
isTotal = true;
//once isTotal true, I need to increment column to check if isTotal still true for the rest of that same row
}
}
}

if ( (i == n) && isTotal )
return true;
}

return false;
}

最佳答案

为了清楚起见,我认为值得将问题分为两部分:

boolean rowIsSumOfTwoOthers(int[][] table) {
int[] sums = sumOfRows(table);
return oneIsSumOfTwoOthers(sums);
}

使用 Java 8 流,这些都相对简单:

private int[] sumOfRows(int[][] table) {
return IntStream.range(0, table.length)
.mapToInt(row -> Arrays.stream(table[row]).sum()).toArray();
}

还有:

private boolean oneIsSumOfTwoOthers(int[] sums) {
return IntStream.range(0, sums.length)
.anyMatch(s1 ->
IntStream.range(0, sums.length)
.filter(s2 -> s2 != s1)
.anyMatch(s2 ->
IntStream.range(0, sums.length)
.filter(s3 -> s3 != s1 && s3 != s2)
.anyMatch(s3 -> sums[s1] == sums[s2] + sums[s3])));
}

关于java - 检查二维整数数组中是否存在一行是同一数组中其他两行的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33770793/

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