gpt4 book ai didi

java - 如何在 Java 中检查二维数组是否占对角线

转载 作者:行者123 更新时间:2023-12-01 18:24:17 26 4
gpt4 key购买 nike

嘿伙计们,我想创建一个函数来检查二维数组是否对角占优

有什么想法吗?

我已经设法找到对角线,但如何检查对角线是否占优?

public static int arraySum(int[][] array){
int total = 0;

for (int row = 0; row < array.length; row++)
{

total += array[row][row];
}

return total;
}

最佳答案

根据Wikipedia ,对角占优矩阵是这样的矩阵:

for every row of the matrix, the magnitude of the diagonal entry in a row is larger than or equal to the sum of the magnitudes of all the other (non-diagonal) entries in that row.

这只是检查弱对角优势,给定一个 2D 数组:

public boolean isDiagonallyDominant(int[][] array) {
int otherTotal = 0;

// Loop through every row in the array
for(int row = 0; row < array.length; row++) {
otherTotal = 0;

// Loop through every element in the row
for(int column = 0; column < array[row].length; column++) {

// If this element is NOT on the diagonal
if(column != row) {

// Add it to the running total
otherTotal += Math.abs(array[row][column]);
}
}

// If this diagonal element is LESS than the sum of the other ones...
if(Math.abs(array[row][row]) < otherTotal) {

// then the array isn't diagonally dominant and we can return.
return false;
}
}
return true;
}

关于java - 如何在 Java 中检查二维数组是否占对角线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26765061/

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